Is it safe to use consumer MLC SSDs in a server?

Question: We (and by we I mean Jeff) are looking into the possibility of using Consumer MLC SSD disks in our backup data center.
We want to try to keep costs down and usable space up - so the Intel X25-E's are pretty much out at about 700$ each and 64GB of capacity.
What we are thinking of doing is to buy some of the lower end SSD's that offer more capacity at a lower price point. My boss doesn't think spending about 5k for disks in servers running out of the backup data center is worth the investment.
These drives would be used in a 6 drive RAID array on a Lenovo RD120. The RAID controller is an Adaptec 8k (rebranded Lenovo).
Just how dangerous of an approach is this and what can be done to mitigate these dangers?
Comment: What is the rationale for using SSD instead of spinners? The folk wisdom on SSD performance is "pay up or don't bother", but there certainly are other aspects that might be an advantage.
Comment: I'm curious about the problem that you're trying to solve here. If it's simply one of costs why are SSDs being considered in place of conventional drives?
Comment: @peterchen, you can use either a couple of SSDs or fifty 15K spindles.
Comment: @iconiK - do you mean  "for a server, you need to spend a lot ofmoney anyway"? If so - yes, that's why I was wondering, too.
Answer: A few thoughts;

SSDs have 'overcommit' memory. This is the memory used in place of cells 'damaged' by writing. Low end SSDs may only have 7% of overcommit space; mid-range around 28%; and enterprise disks as much as 400%. Consider this factor.
How much will you be writing to them per day? Even middle-of-the-range SSDs such as those based on Sandforce's 1200 chips rarely appreciate more than around 35GB of writes per day before seriously cutting into the overcommitted memory.
Usually, day 1 of a new SSD is full of writing, whether that's OS or data. If you have significantly more than >35GB of writes on day one, consider copying it across in batches to give the SSD some 'tidy up time' between batches.
Without TRIM support, random write performance can drop by up to 75% within weeks if there's a lot of writing during that period - if you can, use an OS that supports TRIM
The internal garbage collection processes that modern SSDs perform is very specifically done during quiet periods, and it stops on activity. This isn't a problem for a desktop PC where the disk could be quiet for 60% of its usual 8 hour duty cycle, but you run a 24hr service... when will this process get a chance to run?
It's usually buried deep in specs but like cheapo 'regular' disks, inexpensive SSDs are also only expected to have a duty cycle of around 30%. You'll be using them for almost 100% of the time - this will affect your MTBF rate.
While SSDs don't suffer the same mechanical problems regular disks do, they do have single and multiple-bit errors - so strongly consider RAIDing them even though the instinct is not to. Obviously it'll impact on all that lovely random write speed you just bought but consider it anyway.
It's still SATA not SAS, so your queue management won't be as good in a server environment, but then again the extra performance boost will be quite dramatic.

Good luck - just don't 'fry' them with writes :)
Comment: It's also not always clear if TRIM is supported on a RAID configuration. Remember, the SSDs are abstracted away from the OS with RAID. Be sure to check with the RAID vendor.
Comment: I meant 400 Chris, specifically the ones used in FC SANs, very spendy though, very.
Comment: One trick to get more reserve space out of a drive is to do the secure erase, then partition it with a large fraction unused. This free space will add to the SSD's performance and lifetime.
Comment: Do you mean 400% for the extra space, or 40%? I was going to edit your answer but couldn't find a citation, so I suppose it could be 400%. (It's a very good point, by the way)
Comment: Just want to +1 with @ZanLynx .. I usually only partition about 80% of the drive when I'm using SSD + Raid.
Comment: there is the SF-1500 though http://www.anandtech.com/show/3661
Comment: didn't know about overcommit...nice and dandy +!
Answer: I did find this link, which has an interesting and thorough analysis of MLC vs SLC SSDs in servers

In my view using an MLC flash SSD array for an enterprise application without at least using the (claimed) wear-out mitigating effects of a technology like Easyco's MFT is like jumping out of a plane without a parachute.

Note that some MLC SSD vendors claim that their drives are "enterprisey" enough to survive the writes:

SandForce aims to be the first company with a controller supporting multi-level cell flash chips for solid-state drives used in servers. By using MLC chips, the SF-1500 paves the way to lower cost and higher density drives servers makers want.
  To date flash drives for servers have used single-level cell flash chips. That's because the endurance and reliability for MLC chips have generally not been up to the requirements of servers.

There is further analysis of these claims at AnandTech.
Additionally, now Intel has gone on the record saying that SLC might be overkill in servers 90% of the time:

"We believed SLC [single-level cell] was required, but what we found through studies with Microsoft and even Seagate is these high-compute-intensive applications really don't write as much as they thought," Winslow said. "Ninety percent of data center applications can utilize this MLC [multilevel cell] drive."
.. over the past year or so, vendors have come to recognize that by using special software in the drive controllers, they're able to boost the reliability and resiliency of their consumer-class MLC SSDs to the point where enterprises have embraced them for high-performance data center servers and storage arrays. SSD vendors have begun using the term eMLC (enterprise MLC) NAND flash to describe those SSDs.
"From a volume perspective, we do see there are really high-write-intensive, high-performance computing environments that may still need SLC, but that's in the top 10% of even the enterprise data center requirements," Winslow said.
Intel is feeding that upper 10% of the enterprise data center market through its joint venture with Hitachi Global Storage Technologies. Hitachi is producing the SSD400S line of Serial Attached SCSI SSDs, which has 6Gbit/sec. throughput -- twice that of its MLC-based SATA SSDs.

Intel, even for their server oriented SSD drives, has migrated away from SLC to MLC with very high "overprovisioning" space with the new Intel SSD 710 series. These drives allocate up to 20% of overall storage for redundancy internally:

Performance is not top priority for the SSD 710. Instead, Intel is aiming to provide SLC-level endurance at a reasonable price by using cheaper eMLC HET NAND. The SSD 710 also supports user-configurable overprovisioning (20%), which increases drive endurance significantly. The SSD 710's warranty is 3 years or until a wear indicator reaches a certain level, whichever comes first. This is the first time we've seen SSD warranty limited in this manner.
Answer: Always base these sorts of things on facts rather than supposition. IN this case, collecting facts is easy: record longish-term read/write IOPS profiles of your production systems, and then figure out what you can live with in a disaster recovery scenario. You should use something like the 99th percentile as your measurement. Do not use averages when measuring IOPS cpacity - the peaks are all that matter! Then you need to buy the required capacity and IOPS as needed for your DR site. SSDs may be the best way to do that, or maybe not.
So, for example, if your production applications require 7500 IOPS at the 99th percentile, you might decide you can live with 5000 IOPS in a disaster. But that's at least 25 15K disks required right there at your DR site, so SSD might be a better choice if your capacity needs are small (sounds like they are). But if you only measure that you do 400 IOPS in production, just buy 6 SATA drives, save yourself some coin, and use the extra space for storing more backup snapshots at the DR site. You can also separate reads and writes in your data collection to figure out just how long non-enterprise SSDs will last for your workload based on their specifications.
Also remember that DR systems might have smaller memory than production, which means more IOPS are needed (more swapping and less filesystem cache).
Answer: Even if the MLS SSD only lasted for one year, in a years time the replacements will be a lot cheaper.   So can you cope with having to replace the MLS SSD when they where out?
Comment: a good point, particularly since they will be in a RAID array.. so long as "too many" of them don't fail at once, this is actually plausible.
Comment: @Jeff, if you can swap some in and out with your desk top PCs, so that don't all get the some usage patten, this will make it less lickly they will all fail at the same time.
Comment: @Jeff, I think to a large extend, Fail == "start to do very slow rights" rathern then "dan't read data"
Comment: don't you love auto-correction :-)
Answer: As the original question is really interesting but all answers are quite old, I would like to give an updated answer.
As of 2020, current consumer SSDs (or at least the one from top-tier brands) are very reliable. Controller failure is quite rare and they correctly honor write barriers / syncs / flushes / FUAs, which means good things for data durability. Albeit using TLC flash, they sport quite good endurance rating.
However, by using TLC chips, their flash page size and program time is much higher than old SLC or MLC drives. This means that their private DRAM cache is critical to achieve good write performance. Disabling that cache will wreak havok on any TLC (or even MLC, albeit with lower impact) write IOPs. Moreover, any write patter which effectively bypasses the write-combining function of the DRAM cache (ie: small synchronous writes done by fsync-rich workload) is bound to see very low performance. At the same time write amplification will skyrocket, wearing the SSD much faster than expected.
A pratical example: my laptop has the OEM variant of a Samsung 960 EVO - a fast M.2 SSD. When hammered with random writes it provide excellent IOPs, unless using fsync writes: in this case it is only good for ~300 IOPs (measured with fio), which is a far cry from the 100K+ IOPs delivered without forcing syncs.
Point is that many enterprise workload (ie: databases, virtual machines, etc) are fsync heavy, being unfavorable to consumer SSDs. Of course if your workload is read-centric, this would not apply; however, if using something as PostgreSQL on a consumer SSDs you can be deluded by the results.
Another thing to consider is the eventual use of a RAID controller with BBU (or powerloss-protected) writeback cache. Most such controllers disable the SSD DRAM private cache, leading to much lower performance than expected. Some controller supports re-enabling it, but not all of them pass down the required sync/barrier/FUAs to get reliable data storage on consumer SSDs.
For example, older PERC controllers (eg: 6/i) announced themselves as write-through devices, effectively telling the OS to not issue cache flushes at all. A consumer SSD connected to such a controller can be unreliable unless its cache is disabled (or the controller using extra undocumented care), which means low performance.
Not all controllers behave in this manner - for exampler, newer PERC H710+ controllers announce themselves as write-back devices, enabling the OS to issues cache flushes as required. The controller can ignores these flushes unless the attached disks have their cache enabled: in this last case, they should pass down the required sync/flushes.
However this is all controller (and firmware) related; being HW RAID controllers black boxes, one can not be sure about their specific behavior and only hope for the best. It is worth noting that open sources RAID implementation (ie: Linux MDRAID and ZFS mirroring/ZRAID) are much more controllable beasts, and generally much better at extracting performance from consumer SSDs. For this reason I use opensource software RAID whenever possible, especially when using consumer SSDs.
Enterprise-grade SSD with a powerloss protected writeback cache are immune from all these problems: having a non-volatile cache they can ignore sync/flush requests, providing very high performance and low write amplification irrespective of HW RAID controllers. Considering how low the prices for enterprise-grade SATA SSDs are nowadays, I often see no value in using consumer SSDs in busy servers (unless the intended workload is read-centric or otherwise fsync-poor).
Answer: A Whitepaper on the differences between SLC and MLC from SuperTalent puts the endurance of MLC and a 10th of the endurance of an SLC SSD but the chances are the MLS SSD's will outlive the hardware you are putting them into anyway. I'm not sure how reliable those statistics/facts are from SuperTalent though.
Assuming you get a similar level of support from the supplier of the MLC SSD's then the lower price point makes it worth a shot.
Comment: 5 year lifetimes for typical desktop use have been mentioned.  If that is an accurate estimate then they are not going to outlive the server in a datacenter environment!
Comment: In the organisations I've worked for we've always put server hardware refresh at 3 years. I was under the impression that was generally accepted best practice but do correct me if I'm wrong.
Comment: @JamesRyan: Although not shown in most calculations, the lifetime is very dependent on the fraction of free space.
Answer: If we set the write quantity problem aside (or prove that consumer level SSDs can handle it), I think SSDs are a good thing to add to enterprise-level environments. You will probably be using the SSDs in a RAID array. RAID5 or RAID6. And the problem with these is that after a single drive failure, the array becomes increasingly vulnerable to failure. And the time to rebuild it depends heavily on the volume of the array. A several TB array can take days to rebuild, while being constantly accessed. In case of SSDs, the RAID-arrays will a) be inevitably smaller b) rebuild time decreases drastically.
Answer: You should just calculate the amount of daily writes you have with your current set-up and compare that with what the manufacturer guarantees their SSD drives can sustain. Intel seems to be the most up-front about this - for example, take a look at their mainstream SSD drive datasheets: http://www.intel.com/design/flash/nand/mainstream/technicaldocuments.htm
Section 3.5 (3.5.4, specifically) of the specs document says that you're guaranteed to have your drive last at least 5 years with 20GB of writes per day. I assume that's being calculated when using the entire drive capacity and not provisioning any free space for writes yourself.
Also interesting is the datasheet regarding using mainstream SSDs in an enterprise environment.
Comment: Unfortunately it is not at all that simple because wear leveling amplifies writes (remember it is designed to spread writes not reduce them) in a manner that is proprietary and can vary hugely in it's effectiveness based on the usage pattern.
Comment: Hm, very good point. Also, losing the TRIM command if using the drives in a RAID setup should also increase the write amplification. I guess it all comes down to each manufacturer's idea of the typical usage pattern.
Answer: I deployed a couple of 32gb SLC drives a couple of years ago as a buffer for some hideously poorly designed app we were using.
The application was 90% small writes (< 4k) and was running consistently (24/7) at 14k w/s once on the SSD drives. They were configured RAID 1, everything was rosy, latency was low!
However roughly one month in and the first drive packed up, literally within 3 hours, the second drive had died as well. RAID 1 not such a good plan after all :)
I would agree with the other posters on some sort of RAID 6 if nothing else it spreads those writes out across more drives.
Now bear in mind this was a couple of years ago and these things are much more reliable now and you may not have a similar I/O profile.
The app has been re-engineered, however as a stop gap which may or may not help you, we created a large ram disk, created some scripts to rebuild/backup the ram disk  and take the hit of a hour or so loss on data/recovery time.
Again, your the life cycle of your data may be different.


IVP and Discontinuity

Question: I am continuing my effort to learn analysis from Thomson Bruckner and Bruckner's book. I ran into an interesting problem relating to Intermediate Value Property (IVP). The problem goes as follows:
Suppse $f$ has IVP on $(a,b)$ and discontinuous at $x_0 \in (a,b)$. Prove that there exists a $y \in \mathbb{R}$ such that $\{x : f(x) = y\}$ is infinite.
My Proof is as follows:
Since $f$ is not continuous at $x_o$, we take a sequence of $x_i \rightarrow x_0$. We have for all $\forall \delta > 0 \ \exists n > N$  $|x_n - x_0| < \delta$. Let us consider a monotone subsequence of $x_i$. Now let  $k > N, \ x_k < x_{k+1} < \cdots < x_{k+m} \cdots < x_0$ be one such sequence. Let us say $\nexists y_i \in (x_k, x_{k+1}), y_{i+1} \in (x_{k+1}, x_{k+2}) \cdots$ such that $f(y_i) = f(y_{i+1}) = f(y_{i+2}) \cdots $ and $f(x_{k+i}) != f(x_{k+j}), \ i \ne j$. We have, $f$ by IVP, takes on all the values between $(f(x_k), f(x_0))$ since by our assumption $\nexists y_i \in (x_{k}, x_{k+1}) \cdots $ such that $f(y_i) = f(y_{i+1}) = \cdots$ i.e. $(f(x_{k+i}), f(x_{k+i+1}))$ are all mutually disjoint, our choice of $x_k$ ensures that $f(x_k)$ has a montonic sub-sequence and $\forall \epsilon > 0 \ \exists m > M, \ |f(x_m) - f(x_0)| < \epsilon$. A contradiction.
Now to my QUESTION, is my proof right? It seems right to me. Thanks in advance to your answer.
Comment: This isn't correct: "We have for all $\epsilon > 0 \ \exists \ \delta > 0$ such $x_n - x_0 < \delta$, but $|f(x_n) - f(x_0)| > \epsilon \ \forall n > N$". What if we have for example $f(x) = \sin(1/x)$ for $x \neq 0$, and $f(x_0) = 0$? This function has the IVP and is discontinuous at $x_0 = 0$, but if you choose $\epsilon > 2$ then there is no corresponding $\delta$.
Comment: (1) You messed up the definition of "$f$ is not continuous at $x_0$". (2) $x_{i+1} \in (x_{i+1}, x_{i+2})$ is a badly chosen notation. Let's use $y_{i} \in (x_i, x_{i+1})$. (3) It is not clear how $f(y_i) = f(y_{i+1}) = \cdots$, indeed you did not give a proof.
Comment: @Bungo, I have fixed my proof. I understand I had the clauses all messed up for continuity definition but that was really not necessary. The proof as I wrote did not express what I was trying to claim. I have rewritten it could you see if it is right?
Comment: @John Ma I have made changes to my proof, could you look at it as well.
Answer: By shifting $f$ horizontally and vertically if necessary, we may assume that $x_0 = 0$ and $f(x_0) = 0$ without changing anything relevant to this problem. (It's not necessary to do this, but it declutters the notation a bit.)
Suppose that $\{x : f(x) = y\}$ is finite for all $y \in \mathbb R$.
Choose any $\epsilon > 0$. There are only finitely many values of $x$ such that $|f(x)| = \epsilon$, and $|f(0)| \neq \epsilon$, so there must be some neighborhood $(-\delta, \delta)$ such that $|f(x)| \neq \epsilon$ for all $x \in (-\delta, \delta)$.
Moreover, there cannot be any $x \in (-\delta, \delta)$ such that $|f(x)| > \epsilon$. (If there were, then by the IVP there would have to be some $x'$ between $0$ and $x$ with $|f(x')| = \epsilon$.)
We must therefore have $|f(x)| < \epsilon$ for all $x \in (-\delta, \delta)$. But we can find such a $\delta$ for any $\epsilon > 0$, so we just proved that $f$ is continuous at $0$, a contradiction.
Comment: Awesome and thanks. I have corrected my proof from earlier as well. If you could be kind enough to look at it again, that would be awesome.

IVP and Discontinuity


Atalho terminal MAC/Linux

Question: Gente como posso criar um atalho no terminal ? tipo ao inves de digitar cd xxxx/xxxx/xxxx eu digitar apenas goDevWeb ?
Obrigado
Comment: A sua pergunta não entra no escopo do SOPT, por isso será fechada como descontextualizada, tente ser mais especifico no que pergunta. Veja na [Central de Ajuda](http://pt.stackoverflow.com/help) [Como Perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Answer: Opa!
É assim:
No seu Mac na pasta usuário abra o arquivo .bash_profile. Pode ser no programa em que você programa.
Ele é oculto. Caso seu Finder não mostre os arquivos ocultos digite o seguindo comando no terminal:
defaults write com.apple.finder AppleShowAllFiles -bool true
Depois disso abra o arquivo .bash_profile.
Agora você cria uma função no arquivo:
goDevWeb(){
    cd xxx/yyyy/wwwww;
}

Depois no terminal na pasta usuario digite assim para compilar o arquivo:
source ~/.bash_profile.
Depois faça o teste.
Comment: deu cert... obrigadoooo
Comment: amigo dentro do propio usuario não tem o arquivo, mesmo usando o comando nao aparece....
Comment: Reinicia o Finder. Com o mouse em cima do ícone do Finder na Dock, segura o Option e clica com o botão direito, clique em Reiniciar.
Comment: nem assim... nao exise um comando no terminal que apra direto pelo vim ?
Comment: Que arquivos ocultos que tem na pasta `usuario` ?
Comment: Applications  Movies   composer.phar
Creative Cloud Files Music   https:
Desktop   NetBeansProjects laravel
Documents  Pictures  mcrypt
Downloads  Public   readme.textile
Google Drive  branches  tags
Library   composer.json  trunk
Comment: amigo apos reiniciar o finder novamente surgiuj varios arquivos, mas nenhum com o nome de bash_profile apenas bash_history bash_session
Comment: Tem algum que chama `.profile` ou `.bashrc` ?
Comment: não. Estou usando a nova versao do mac a que saiu por ultimo ....
Comment: Lista atualizado dos arquivos ao usar ls -a : .   .netbeans-derby  Movies
..   .oracle_jre_usage Music
.CFUserTextEncoding .p2   NetBeansProjects
.DS_Store  .putty   Pictures
.Trash   .ssh   Public
.WebIde100  .subversion  branches
.WebStorm10  .svn   composer.json
.WebStorm11  .viminfo  composer.phar
.android  Applications  https:
.bash_history  Creative Cloud Files laravel
.bash_sessions  Desktop   mcrypt
.composer  Documents  readme.textile
.config   Downloads  tags
.eclipse  Google Drive  trunk
.gradle   Library
Comment: Então cria um arquivo `.bash_profile` e faça isso que te falei.

Atalho terminal MAC/Linux


Why normal repeated multiplication of power algorithm is not efficient?

Question: As the question , i dont understand why we need some algorithm like exponential by squaring or modular exponentiation for calculating the power of a number.
For example, i have a repeated multiplication algorithm like this :
def expt_mul(a, n):
    r = 1
    for i in xrange(n):
        r *= a
    return r

a multiplied by itself n times , so the complexitiy is O(n), why it's not efficient?
Comment: Efficiency is relative. Why have O(n) when you can have O(log(n))?
Comment: Just to point out that sequential multiplication isn't efficient:  For the special case of computing a^4, your code takes 3 multiplies.  But you could do it as `a2=a*a; a4 = a2*a2;` which takes only 2.  There's a lot written about this, see http://en.wikipedia.org/wiki/Exponentiation_by_squaring.
Comment: The complexity is O(b), not O(n) (or we must assume n=b) :)
Comment: O(log(n)) provides an upper bound, but no theoretical lower bound exists, so the best way to answer your question is to do statistical tests using the language, operating system, etc. that your product uses.
Comment: It's worth noting (but not on an answer) that in this case O(n) is considered an exponential algorithm, since the input itself is Ω(log n) in size. So, if you are talking about a b-bits number, the O(n) algorithm is really O(2^b).
Answer: In encryption, for an example, it's common to do exponentiations where the exponent can be on the order of 2100 or more.  Assuming you can do 1010 multiplications per second, you're talking about needing something on the order of 1020 seconds.  Expressed that way, you might shrug and say "so what?", so let's convert that to years:  1020 seconds / 3600 sec/hour / 24 hr/day / 365.25 days/year / 14E9 years/current age of universe => over 226 times the current age of the universe!  Contrast that with a logarithmic time algorithm, which will do 2100 exponentiation in a few hundred operations--almost instantaneously from your perspective.
Answer: Some algorithms require raising numbers to very large powers. Algorithms from cryptography in particular come to mind, such as the Diffie-Hellman key exchange.
While your algorithm might be fine for most everyday tasks, when you're dealing with exponents that are very large, it becomes unfeasible to use, so exponentiation by squaring is used instead.

why we need some algorithm like exponential by squaring or modular exponentiation for calculating the power of a number.

Note that exponentiation by squaring does not achieve the same thing as modular exponentiation. The first is an efficient algorithm to raise an entity to a certain integer power, while the latter is a method to compute an expression of the form (a^b) modulo c, where the algorithm used for exponentiation is not particularly relevant.


Playing with other musicians

Question: This is a soft question. I've been learning the bass for about 6 months now and I can play some odd time signatures with ease when I'm practicing alone. Recently, I've been playing with a couple of friends, one drummer and another, guitarist. I'm having a lot of difficulty keeping time when playing with this drummer.
My question is: Is this normal? I didn't assume there were going to be no challenges when playing with other people but I'm struggling to play in time (even something at 60bpm).
One issue I can think of is that I'm easily distracted by the guitar and I lose focus. What are some things I should keep in mind when playing with them again? Thanks for your time.
Edit: After considering the several answers and suggestions, I firstly tried to find out who all among us is out of time and not surprisingly, all 3 of us were dragging, not just me. I intend to play with only the drummer a couple more times a week than with all 3 together, to get the rhythm down solid. I've proposed that we play at lower than usual volumes using a metronome and that the drummer try playing gentler. Of course, a co-ordination issue like this wont solve itself overnight but I plan to work it out in the following few days to weeks.
Comment: why do you feel distracted by the guitar? e.g. can you not hear yourself well?
Comment: @topomorto It's not the volume, but now that you mention it, I can't hear anything from my E and A strings if the guitar is playing along. But I just assumed that that's how it is, since the human ear is not as sensitive to lower frequencies. Or is that not how it should be?
Comment: Whatever amp you play through, the volume *all* of you play at needs to be such that each player can hear the other. That does not mean each keeps turning up more. In fact, pros will do the opposite - each turn down  (including the drummer - yes, good ones can and do play quietly!) *so* they can hear each other properly.
Comment: @Tim I can imagine managing with 40 Watts, a cab that can manage a bit of low end, and a considerate drummer. The only frontman bass amp I can find reference to only claims 15W (https://www.fmicassets.com/Damroot/Original/10003/Frontman%2015B.pdf) which to my mind makes it more of a practice-on-your-own amp than a practice-with-the-band amp - I've not actually used one though.
Comment: That is not how it should be. What amp are you playing through?
Comment: @topomorto It's a Fender frontman. It was a used one I bought at some kind of flea market.
Comment: Is it the frontman 15b?
Comment: @Tim wise advice in general - if a bass amp is *too* small though, it might have so little oomph at lower frequencies (OP mentioned problems with  E and A strings) that a drummer might have to play comically quietly to get the balance right. As a very rough rule of thumb, a bass amp in the 100 Watt range is often said to be what you need to play with a drummer.
Comment: @topomorto - on my acoustic kit, I use muffling rings, which take volume down well. Also, using rutes makes playing quieter. In a rehearsal situation - which I guess this scenario is - I've used 40 watt bass amps without worries. I suppose what I mean is any drummer can play loudly, whereas a lot *can't* play quietly.
Comment: Incidentally, a slower bpm wouldn't make it easier to play (or feel like you're playing) in time, except for technically difficult passages. It makes you rely more on a strong internal metronome and accentuates any slight desynchronization.
Answer: First is to record what you all do when playing together. It could be any one of you that's throwing timing out. Listen back, and you'll have a far better idea.
In one band I played bass, and the drummer and I couldn't gel. He insisted his timing was spot on, until we listened to a few recordings, when even one of the guitarists told him he was fluctuating in his timing.
Try playing with one or the other, and work out what's going on. Keep your parts very simple, but spot on timing, by isolating what you play, while still being part of the jigsaw.
Play along with a metronome (or simple drum machine) - and insist the others do too. You'll soon find who's out.
At home, play along with tracks, get someone to turn down the volume, and keep playing. You should manage several bars, and still be in time when the track gets turned up again.
It may be that everyone is playing so loudly that no-one can listen to the others. Happens way too many times! Try all playing at half volume. It helps a lot when everyone hears everything.
Comment: Yes, it should've occurred to me that it's possibly not just me who's out of time. I will do as you've advised and will post an edit to this question once I've found a way to keep time.
Answer: It's worth realising that the bass guitar is part of the rhythm section. It is vital that the bass and drums are together. They lay down a clear framework over which the lead instruments can deliberately play ahead or behind the beat.
It is worth just you and the drummer practising together before anyone else joins in (even arrange a separate session). The other players can listen and give feedback. In practice get a simple 12 bar blues bass riff going with just you and the drummer. Insist that the lead instruments don't join in until everything is synchronised.
What you will find is that either you or the drummer isn't listening to the other.
Drummers are used to setting the tempo, and, if inexperienced they can forget that others are playing and assume that everyone will stick with them. This is usually part of the personality of a drummer!
A good tip is to play bass in time with the kick drum (bass drum). This combined sound is very powerful. The drum gives the bass sound punch, and the bass gives the drum a melodic nature.
If the drummer will co-operate you can get them to simply play kick drum and high-hat alongside your bass line. Get that perfectly synchronised and you'll find you and the drummer are actually listening to each other.
Comment: That **listening** part is so important. Listening *to each other*. Played with a lot of drummers who part listen, but then allow the excitement of the moment make them speed up. I do it myself on drums, sometimes, and have to **listen** even more carefully. But all musos should be listening to each other - all the time - otherwise we become voices in the wilderness, and not part of a team. +1.
Answer: It could even be that both are listening to  each other and they don't find each other.
I will give you another example: We used to go singing in the restaurants and pubs when I was young and sometimes we just improvised and had no program who will sing the melody part of a song and who the background or the second voice. As we played guitar we also couldn't give a sign who should sing which part. So it sometimes could happen that both were singing the upper voice and when realizing it both changed to the lower voice.
So what happend in this example with low and high could also happen between bass and drummer with faster and slower. (In this case this would only  be the expression of good will of both of you.)
There are more possibilities not to fall in this trap:

You can both decide by a sign that only one is responsible for the timing of the beat.
You accept an external  accustical or optical metronome, which will be objectif.

Playing with other musicians


Is the fingering strange in Saint-Saens piano version (from Liszt) of Danse macabre

Question: In Saint-Saens piano version (from Liszt) of Danse macabre, m. 79,
there is this left hand fingering (that I show in blue)
Is it a good fingering ?
(it looks like 3 2 would be much more natural and easy)
Answer: This is an error in the score, which is corrected in the Neue Liszt-Ausgabe edition, shown below.

(Image source: IMSLP)
Answer: You're right - swapped over makes more sense. Probably a misprint. Fingering is for guidance only, I encourage students to use what they consider best for them, which may be different from that printed. Suggest you do the same!
Comment: This information is capital. Let's see if somebody disagree or agree with you. I will validate your answer in 24 hours if nobody states an "opposite answer".


KVM public ip setup with subnet /29

Question: I have a dedicated server from hetzner with one additional /29 subnet
i have configured a bridge network which looks fine to me
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master
br0 state UP group default qlen 1000
link/ether 00:1e:67:99:85:cf brd ff:ff:ff:ff:ff:ff
inet6 fe80::21e:67ff:fe99:85cf/64 scope link
   valid_lft forever preferred_lft forever

3: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state
UP group default qlen 1000
link/ether 00:1e:67:99:85:cf brd ff:ff:ff:ff:ff:ff
inet 184.108.40.206/27 brd 220.127.116.11 scope global br0
   valid_lft forever preferred_lft forever
inet 184.108.40.206/29 brd 220.127.116.11 scope global br0:1
   valid_lft forever preferred_lft forever
inet6 fe80::21e:67ff:fe99:85cf/64 scope link

I installed a guest machine with Ubuntu 18 os and assigned a static ip
addresses: 184.108.40.206/29
gateway4: 188.8.131.52

But i cant connect vm to public ip
I am using Kimchi and Wok as GUI interface for management
Question 1:
 How many public ip do have now as useable 5 or 6?
Question 2:
 How can i bind these public ip with libvirt kvm
Comment: You must configure IP addresses in the VM, not in the host.
Comment: I configured on the VM.. but it doesnt ping or resolve to internet.
Answer: I'm not an expert on networks but

I'd think the gateway must be on a reachable network. Your VM is on 126.96.36.199/29 but the gateway is outside the range 184.108.40.206-118.
The VM needs a specific IP address from the range 220.127.116.11-118. (112 and 119 are not allowed.)
While you can configure your VM host to have 22.214.171.124 and act as a gateway to the VMs, I'd first try without gateway so that you can use 113 for a VM. (I'm not sure whether it is possible to have no gateway.)
If you need a gateway for your VMs, you need to set up the host to have an address on the VM network, e.g. 22.214.171.124, and to route between the VM network and the network that gives you internet access. Probably the later network has a gateway 22.214.171.124. If you can connect to your server over the network (rather than the hetzner web-interface) this should be in working order.

KVM public ip setup with subnet /29


Name property missing in activity.from object in messageReaction

Question: I am testing an MS Teams bot and have implemented an onReactionsAdded event like below.
this.onReactionsAdded(async (context, next) => {
    var name=context.activity.from.name;
    .
    .
    .
}

But the name property and value are missing
  reactionsAdded: [ { type: 'laugh' } ],
  type: 'messageReaction',
  timestamp: 2021-03-31T12:26:50.115Z,
  id: '161719353xxx',
  channelId: 'msteams',
  serviceUrl: 'https://smba.trafficmanager.net/emea/',
  from: {
    id: '29:1lejmc96kXSbnIvqlxxxxxxxxx27Sm_-XNA-CWdIrI_OxL5xBxxxxxxxxxxxxxxxxxxxxxx',
    aadObjectId: '59a26b60-1ca9-4cf0-a4e8-xxxxxxxxxxxxx'
  },

The activity.from in onMessage contains the Name
this.onMessage(async (context, next) => {
    var name=context.activity.from.name;
    .
    .
    .
}

{
  text: 'fds',
  textFormat: 'plain',
  type: 'message',
  timestamp: 2021-03-31T12:25:37.809Z,
  localTimestamp: 2021-03-31T12:25:37.809Z,
  id: '1617fds794',
  channelId: 'msteams',
  serviceUrl: 'https://smba.trafficmanager.net/emea/',
  from: {
    id: '29:ccccccxxxxlZUuykg027Sm_-XNA-CWdIrI_OxfxxxxzD6AUmRJ1F8D5E96nw',
    name: '<Some name>',
    aadObjectId: '59a26b60-1ca9-4cf0-a4e8-xxxx'
  }

Comment: What is your question?
Comment: Could you please elaborate your question.
Comment: Why is the "Name" property missing in the messageReaction response?
Comment: @InnovateIt - I don't know. That sounds like a bug. Why not report it to Teams instead of Stack Overflow? Though I'm wondering about something... it looks like the two activities in your question are coming from two different users. Is that the case, and could that account for the difference? Have you looked at a message activity and a message reaction activity from the same user? (Since there are multiple other people in this thread, you will need to @ mention me if you want me to see your reply.)
Comment: @InnovateIt: It seems name is not expected in messageReaction. See the reference here: https://learn.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bots-notifications#schema-example-a-user-likes-a-message.  Id and aadObjectId is only given in response
Comment: @InnovateIt - Are you still working on this?
Answer: As @subba-reddi-tummuru writes, the response does not contain the name property according to the documentation


jQuery Show and Hide with Speed Not Exiting For Loop

Question: I'm trying to show/hide a block of input fields based on the value of a  box. It works fine if I stick with show() and hide() but as soon as I put in a speed show(100) and hide(100) things break.
What should happens is:

If value of select is an item found in an array then the block should show.
If the value of the select is not an item found in an array then the block should not show.
If the value of the select is an item found in an array and the block is visible nothing should happen.

jsFiddle example code: http://jsfiddle.net/PkBg6/

Retail Individual should not show the block
Employee should not show the block
Everything else should show the block

HTML

    Customer Type

    <select data-required="false" id="customerType">
        <option value="retailIndividual">Retail Individual</option>
        <option value="retailBusiness">Retail Business</option>
        <option value="dealer">Dealer</option>
        <option value="raceTeam">Race Team</option>
        <option value="membershipClub">Membership Club</option>
        <option value="employee">Employee</option>
    </select>

        Business Name
        <input type="text" id="businessName" data-required="true" />

        Department
        <input type="text" id="department" data-required="false" />

JavaScript
$.fn.toggleFieldset = function(stringText, x) {
    var arrayText = stringText;

    for(var i = 0; i < arrayText.length; i++) {
        if( $(this).val() == arrayText[i] ) {
            $(x).show();
            return;
        }

        else {
            $(x).hide();
        }
    }

    $(this).on('change', function() {
        for(var i = 0; i < arrayText.length; i++) {
            if( $(this).val() == arrayText[i] ) {
                $(x).show(100);
                console.log('show');
                return;
            }

            else {
                $(x).hide(100);
                console.log('hide');
            }
        }
    });
};

$(document).ready(function () {
    $('#customerType').toggleFieldset(['retailBusiness', 'dealer', 'raceTeam', 'membershipClub'], '#groupMember');
});

Comment: Try `fadeIn` and `fadeOut`. Also you forgot to declare `i` and `return` exits the function so the `else` is redundant.
Comment: @elclanrs I will declare the `i`. I tried `fadeIn` and `fadeOut` but I'm still having the same problem. I'm not sure how the `else` is redundant though because if nothing matches then it should execute the `else`. Thanks!
Answer: The else clause is getting run when you don't want it to. When say dealer is selected it gets executed when compared to retailBusiness which hides it then it gets shown when it matches itself again. Here is the onchange function which worked for me.
$(this).on('change', function() {
    var match = false;
    for(var i = 0; i < arrayText.length; i++)
        if( $(this).val() == arrayText[i] )
            match = true;
    if( match ) {
       $(x).show(100);
       console.log('show'+arrayText[i]);
       return;
    }
    else {
       $(x).hide(100);
       console.log('hide'+arrayText[i]);
    }
});


Why did someone come up with the formula $\mathbf{P}^{-1}\mathbf{AP}=\mathbf{D}$?

Question:
For Diagonalizable matrix
I wonder why/how someone came up with the formula:
$$\mathbf{P}^{-1}\mathbf{AP}=\mathbf{D}$$
and not something else like following:
$$\mathbf{AP}=\mathbf{D} $$
$$\text{or}$$
$$\mathbf{PA}=\mathbf{D}$$
Comment: @sdsad: do you mean intuition behind diagonalization?
Comment: Can you give some more context? What is P, D and A?
Comment: @ChinnapparajR yeah i think that's what he's asking
Comment: That is correct :-)
Answer: Let ${X_1}, {X_2} \cdots {X_n} $ be independent Eigen vectors of a square matrix A corresponding to the Eigen values $\lambda_1, \lambda_2, \cdots , \lambda_n$.
Let $P = [{X_1} \  {X_2} \cdots {X_n}]$ be the matrix with columns containing Eigen vectors.
Also we have, $$A{X_i} = \lambda_i{X_i}$$
So, $$AP  = [A{X_1} \  A{X_2} \cdots A{X_n}] = [\lambda_1{X_1} \  \lambda_2{X_2} \cdots \lambda_n{X_n}]$$
$$AP = [{X_1} \  {X_2} \cdots {X_n}]\begin{bmatrix}\lambda_1 & 0 & \cdots & 0 \\0 &\lambda_2 &\cdots & 0
\\ \vdots & \vdots& \vdots & \vdots \\ 0 & 0 & \cdots &\lambda_n \end{bmatrix} $$
$$AP = PD$$
where $D$ is the diagonal matrix. $P$ is invertible as the Eigen vectors are independent and $|P| \not= 0$.
So,

$$P^{-1}AP = D$$

We can compute the higher indices of $A$ from the above equation.
$$D^2 = P^{-1}A^2P$$
$$D^3 = P^{-1}A^3P$$
$$\vdots$$
$$D^k = P^{-1}A^kP$$
or

$$A^k = PD^kP^{-1}$$

So, it is conventional to write it as $P^{-1}AP = D$
Comment: Not really. You derive the formula by using eigenvectors. But why do you even think about eigenvectors and not anything else? My question is more about the intuition for how someone ended up with this formula - like why did they think about eigenvectors and not any other construct
Comment: Thanks. But still, why would you think about eigenvectors in the first place?
Comment: Are you asking about the isolation in $$AP = [{X_1} \  {X_2} \cdots {X_n}]\begin{bmatrix}\lambda_1 & 0 & \cdots & 0 \\0 &\lambda_2 &\cdots & 0
\\ \vdots & \vdots& \vdots & \vdots \\ 0 & 0 & \cdots &\lambda_n \end{bmatrix}$$ ?
Comment: Possibly worth reading: [What is the importance of eigenvalues/eigenvectors?](https://math.stackexchange.com/questions/23312/what-is-the-importance-of-eigenvalues-eigenvectors)
Answer: For a linear transformation $A$ on a vector space (finite) $U$, we know that $A$ can be `represented' by a matrix. We usually denote this matrix by $[A]_{\mathcal{B}}$, where $\mathcal{B}$ is a basis for $U$.
Taking the basis for $U$ consisting of eigenvectors of  $A$ (when this is  possible, i.e. when $A$ has $dim(U)$ linearly independent eigenvectors), gives a particularly simple (diagonal) $[A]_{\mathcal{B}}$ (this is your $D$).
Answer: The defining equation for eigenvectors is $A\mathbf v=\lambda\mathbf v$. If we have a bunch of eigenvectors $\mathbf v_i$ with associated eigenvalues $\lambda_i$, using basic properties of matrix multiplication we can collect up all of the individual equations into a single "bulk" equation $$A\begin{bmatrix}\mathbf v_1 & \cdots & \mathbf v_n\end{bmatrix} = \begin{bmatrix}\mathbf v_1 & \mathbf v_2 & \cdots & \mathbf v_n\end{bmatrix} \begin{bmatrix}\lambda_1 & 0 & \cdots & 0 \\ 0&\lambda_2&\cdots&0 \\ \vdots & \vdots & \ddots & \vdots \\ 0&0&\cdots&\lambda_n\end{bmatrix},$$ or $AP=PD$ for short. Note that the matrix of eigenvalues right-multiplies the eigenvector matrix: we want to multiply each column of $P$ by the appropriate value.
If $A$ is diagonalizable, we can choose eigenvectors $\mathbf v_n$ such that they form a basis for the space, in which case $P$ will be square and invertible, so we can multiply both sides by $P^{-1}$ to get $P^{-1}AP=D$. I often use the equation $AP=PD$ as a starting point because I can never remember which side the inverse matrix goes on and it's easy to derive from the fundamental eigenvector equation.
Comment: An easy way to remember is by noting that $D $ operates on coordinate vectors with respect to basis of eigenvectors. So on the LHS of the matrix equation we need a vector expressed as coordinate vector wrt basis consisting of eigenvectirs  The columns of this transition matrix  are the eigenvectors as coordinate vectors wrt to the standard basis. Hence we apply $P $ to get a vector wrt standard basis, so that $A $ can be applied to it (if $A $ is standard matrix representation of our linear transfirmation).
Comment: @AnyAD As Señor Wences used to say, "Easy for you; hard for me." $A\mathbf v=\lambda\mathbf v$ is ingrained in stone. The rest is an almost trivial symbolic manipulation. For other things, remembering "input" and "output" bases is indeed easy.
Comment: Don't disagree. (Thinking about transition matrices is sometimes useful, obviously depending on what one is trying to highlight)


Unable To Remove DPM Agent

Question: I have installed the DPM 2010 Agent on a Windows Server 2003 that act as a Secondary AD. Since it was demoted, I'm unable to get DPM to work.
According to this :
http://technet.microsoft.com/en-us/library/ff399208.aspx
I need to remove the current DPM agent and reinstall it again.
Problem :
The DPM doesn't show up on Add/Remove.
I can't find the uninstaller or a CLI option.
The current DPM server doesn't see this agent , so remote uninstall is not an option.
How can DPM Agent be removed?
Answer:
Run PowerShell (The DPM management shell) as administrator.
In DPM 2010 PowerShell write "remove-productionserver.ps1". Press enter
You will be prompted to enter the DPMServername, write your DPM server name that you are trying to remove the DPM agent from. Press Enter
Then write the DPM agent name that you trying to remove. Press Enter
You will be prompted that the agent is been removed and you will see the agent is been removed from the DPM 2010 Management agents tab.

On the agent:
If it's not showing up in Add/Remove programs, try:
For a 32-bit operating system, at the command prompt type
Msiexec /x {07CCDE6A-1D92-2C9C-D091-9E682643ABCC}

For 64-bit operating system, at the command prompt type
Msiexec /x {72BF00D8-53E0-1539-F523-4347082BCC11}

PS - Writing MS with a dollar sign stopped being cool about 15 years ago.
Sources:
http://technet.microsoft.com/en-us/library/ff629522.aspx
http://laithalmashta.blogspot.com/2011/09/cannot-remove-dpm-2010-agent-from-dpm.html
Comment: Hello Ryan. Windows Reports This App. Is Not Installed When Using The Commands Above.

Unable To Remove DPM Agent


How can I solve this build error: "no matching function for call to" in C++ under UNIX?

Question: How can I solve this build error: "no matching function for call to" in C++ under UNIX?
I am getting the following build error:
unixserver:Lab1> make
g++ -o LSL lab1.cpp Employee.cpp
lab1.cpp: In function int main():
lab1.cpp:199: error: no matching function for call to LinkedSortedList<Employee>::find(std::string&)
LinkedSortedList.cpp:137: note: candidates are: bool LinkedSortedList<Elem>::find(Elem) const [with Elem = Employee]
make: *** [main] Error 1

Here is my find function:
// Check to see if "value" is in the list.  If it is found in the list,
// return true, otherwise return false.  Like print(), this function is
// declared with the "const" keyword, and so cannot change the contents
// of the list.
template<class Elem>
bool LinkedSortedList<Elem>::find(Elem searchvalue) const {
         if (head == NULL) {
                 return false;
         } else {
                 while (head != NULL) {
                    LinkedNode<Elem>* pointer;
                    for (pointer = head; pointer != NULL; pointer = pointer->next)
                        if (pointer->value == searchvalue) {
                            return true;
                        }
                  }
         }
         return false;
 }

And this is in my LinkedSortedList.h file under the "public:" section:
bool find(Elem searchvalue) const;

Here is the missing code: line 199
                        case 'S':
                                cout << "Save database to a file selected\n\n";
                                // TODO call function to save database to file
                                // File I/O Save to file
                                cout << "Please enter a file name: " << endl;
                                cin >> fileName;
                                {char* file = (char*) fileName.c_str();
                                writeFile(file, database);}
                                break;

Comment: Please don't post line numbers in your code like this; it makes it very difficult for anyone to copy and paste into an editor.
Comment: Also, you haven't posted the code that's causing the error (i.e. line 199 and any other relevant lines above it).
Comment: Please format your code.  And the compiler output example.
Comment: I posted the missing code, sorry about that.
Comment: How do you format code when making a post?
Answer: Your problem is, as the error message states, that you are trying to invoke this function:
LinkedSortedList::find(std::string&)

but it doesn't exist.
You have three options:

Create that function. In the public section of LinkedSortedList declare (and subsequently implement) something like find(const std::string&);
Don't invoke that function. In your test program, call list.find(elem) instead of list.find(str), for example.
Make Employee implicitly constructable from std::string. Add a new public constructor to Employee that takes a single std::string as a parameter.


In a convolutional neural network (CNN), when convolving the image, is the operation used the dot product or the sum of element-wise multiplication?

Question: The example below is taken from the lectures in deeplearning.ai shows that the result is the sum of the element-by-element product (or "element-wise multiplication".  The red numbers represent the weights in the filter:
$(1*1)+(1*0)+(1*1)+(0*0)+(1*1)+(1*0)+(0*1)+(0*0)+(1*1)
= 1+0+1+0+1+0+0+0+1
= 4 $

HOWEVER, most resources say that it's the dot product that's used:

"…we can re-express the output of the neuron as , where is the bias
  term. In other words, we can compute the output by y=f(x*w) where b is
  the bias term. In other words, we can compute the output by
  performing the dot product of the input and weight vectors, adding in
  the bias term to produce the logit, and then applying the
  transformation function."

Buduma, Nikhil; Locascio, Nicholas. Fundamentals of Deep Learning: Designing Next-Generation Machine Intelligence Algorithms (p. 8). O'Reilly Media. Kindle Edition.

"We take the 5*5*3 filter and slide it over the complete image and
  along the way take the dot product between the filter and chunks of
  the input image.  For every dot product taken, the result is a
  scalar."

https://medium.com/technologymadeeasy/the-best-explanation-of-convolutional-neural-networks-on-the-internet-fbb8b1ad5df8

"Each neuron receives some inputs, performs a dot product and
  optionally follows it with a non-linearity."

http://cs231n.github.io/convolutional-networks/

"The result of a convolution is now equivalent to performing one large
  matrix multiply np.dot(W_row, X_col), which evaluates the dot product
  between every filter and every receptive field location."

http://cs231n.github.io/convolutional-networks/
However, when I research how to compute the dot product of matrics, it seems that the dot product is not the same as summing the element-by-element multiplication. What operation is actually used (element-by-element multiplication or the dot product?) and what is the primary difference?
Comment: Dot product is not accurate. I would say it's sum of the `Hadamard product` between the selected area and convolution kernel.
Comment: its a dot product but instead of using the whole matrix sums patches that are moved along, so we couldnt use the dot product function cause we would have to loop passing different matrices moving the patch/window around all the image/matrix
Answer: Any given layer in a CNN has typically 3 dimensions (we'll call them height, width, depth). The convolution will produce a new layer with a new (or same) height, width and depth. The operation however is performed differently on the height/width and differently on the depth and this is what I think causes confusion.
Let's first see how the convolution operation on the height and width of the input matrix. This case is performed exactly as depicted in your image and is most certainly an element-wise multiplication of the two matrices.
In theory:
Two-dimensional (discrete) convolutions are calculated by the formula below:
$$C \left[ m, n \right] = \sum_u \sum_υ A \left[ m + u, n + υ\right] \cdot B \left[ u, υ \right]$$
As you can see each element of $C$ is calculated as the sum of the products of a single element of $A$ with a single element of $B$. This means that each element of $C$ is computed from the sum of the element-wise multiplication of $A$ and $B$.
In practice:
You could test the above example with any number of packages (I'll use scipy):
import numpy as np
from scipy.signal import convolve2d

A = np.array([[1,1,1,0,0],[0,1,1,1,0],[0,0,1,1,1],[0,0,1,1,0],[0,1,1,0,0]])
B = np.array([[1,0,1],[0,1,0],[1,0,1]])
C = convolve2d(A, B, 'valid')
print(C)

The code above will produce:
[[4 3 4]
 [2 4 3]
 [2 3 4]]

Now, the convolution operation on the depth of the input can actually be considered as a dot product as each element of the same height/width is multiplied with the same weight and they are summed together. This is most evident in the case of 1x1 convolutions (typically used to manipulate the depth of a layer without changing it's dimensions). This, however, is not part of a 2D convolution (from a mathematical viewpoint) but something convolutional layers do in CNNs.
Notes:
1: That being said I think most of the sources you provided have misleading explanations to say the least and are not correct. I wasn't aware so many sources have this operation (which is the most essential operation in CNNs) wrong. I guess it has something to do with the fact that convolutions sum the product between scalars and the product between two scalars is also called a dot product.
2: I think that the first reference refers to a Fully Connected layer  instead of a Convolutional layer. If that is the case, a FC layer does perform the dot product as stated. I don't have the rest of the context to confirm this.
tl;dr The image you provided is 100% correct on how the operation is performed, however this is not the full picture. CNN layers have 3 dimensions, two of which are handled as depicted. My suggestion would be to check up on how convolutional layers handle the depth of the input (the simplest case you could see are 1x1 convolutions).
Comment: Yes what I wanted to point out is that this is equivalent to a dot product between the vector of pixels along the third dimension (depth, filters call it what you want) and the scalar weight of the convolution kernel.
Comment: thanks for response.  Per your suggestion about researching how convolutional layers handle the depth of the input- see the Convolution Demo section at this link: http://cs231n.github.io/convolutional-networks/ .  I computed the numbers in a spreadsheet and it appears that the final number that goes in the output volume is just the sum of the element-wise multiplication of each filter and receptive field (which sum to one number per color volume), and then the three numbers are just added up along with the bias...
Answer: I believe the key is that when the filter is convolving some part of the image (the "receptive field") each number in the filter (i.e. each weight) is first flattened into vector format.  Likewise, the pixels of the image are also flattened into vector format.  THEN, the dot product is calculated.  Which is the exact same thing as finding the sum of the element-by-element (element-wise) multiplication.
Of course, these  flattened vectors can also be combined in a matrix format, as the below image shows.  In this case then true matrix multiplication can be used, but it's important to note that the flattening the image pixels from each convolution and also the weights filter is the precursor.

image credit: TensorFlow and Deep Learning without a PhD, Part 1 (Google Cloud Next '17)
Comment: Python code for illustration https://gist.github.com/alexcpn/0378e092d1d6c9a8c432a38bf6cceb37
Answer: The operation is called convolution which involves a sum of element by element multiplication, which in turn is the same as a dot product on multidimensional matrices which ML folks call tensors. If you write it as a loop, it'll look like this pseudo Python code:
for i in 0:3:
  for j in 0:3:
    s = 0
    for k in 0:3:
      for l in 0:3:
        s += A[i+k,j+l]*C[k,l]
    Z[i,j] = s

Here A is your 5x5 input matrix, C is 3x3 filter and Z is 3x3 output matrix.
The subtle difference with a dot product is that usually a dot product is on the entire vectors, while in convolution you do dot product on the moving subset (window) of the input matrix, you could write it as follows to replace the innermost two nested loops in the code above:
Z[i,j] = dot(A[i:i+2,j:j+2],C)

Comment: The first line isn't technically correct. The vectorized dot product is *one type* of convolution, but not the only one.
Answer: Both element-wise and dot product interpretations are correct. When you convolve two tensors, X of shape (h, w, d) and Y of shape (h, w, d), you're doing element-wise multiplication. It's, however, the same as the dot product of X and Y transpose. You can expand the math equation, the shapes and subscripts match.
Comment: The first line isn't technically correct. The vectorized dot product is one type of convolution, but not the only one.
Answer: "What operation is actually used (element-by-element multiplication or the dot product?) and what is the primary difference?"
The actual operation is called a convolution defined as:
$$ J(x,y) = K * I = \sum_{n,m}K(n,m)I(x-n,y-m)  $$
Where $J$ is the convolved signal, $K$ is the kernel, $I$ is the input signal, and $n,m$ are the kernel indexes. We see by the input signal indexing $I(x-n,y-m)$ that both input signal axes are "flipped". As an aside, the kernel (a.k.a. filter) could be flipped instead.
Back to your question:
From the Numpy docs: the dot product numpy.dot "Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. (...)"
While the sum of the element-wise multiplication returns a scalar.
Making use of a previous reply - if we look at the two regions in the example:
import numpy as np
from scipy.signal import convolve2d

A = np.array([[1,1,1],
              [0,1,1],
              [0,0,1]])

B = np.array([[1,0,1],
              [0,1,0],
              [1,0,1]])

Dot product (returns ndarray):
print(np.dot(A,B))

[[2 1 2]
 [1 1 1]
 [1 0 1]]

Sum of element-wise multiplication (returns scalar);
print(np.sum(np.multiply(A,B)))

4

And that is the primary difference.
For good measure, a convolution:
D = convolve2d(A, B, 'valid')
print(D)

[[4]]

which in this case is equal to sum of element-wise multiplication of image patch and filter.
A convolution can be equivalent to sum of element-wise multiplication if the filter is symmetric, which is the case in deeplearning.ai example given. This will not be the case for asymmetric filters:
B2 = np.array([[1,0,0],
               [0,1,0],
               [1,0,1]])

print(np.sum(np.multiply(A,B2)))
print(convolve2d(A, B2, 'valid'))

3
[[4]]

where sum of element-wise multiplication returns 3 and convolution returns 4, albeit as numpy.ndarray data type.
Note the discussion on flattened arrays - TensorFlow and Deep Learning without a PhD, Part 1 (Google Cloud Next '17) - applies to fully-connected, not convolutional layers.
2020 are you still reading? :D


Semicubical parabola coordinate ring

Question: Let $C=\{(x,y)\in\mathbb{A}^2 \colon y^2-x^3=0\}$. Let $k[C]=k[x,y]/(y^2-x^3)$ be the coordinate ring of $C$. I read in a book that $k[C]$ is non a UFD. Is there a not too difficult and deep way to see this?
Answer: UFDs are integrally closed. But $t = y/x$ is in $k(C) \setminus k[C]$ and integral over $k[C]$, since $t^2=x$.
Alternative: $x \in k[C]$ is irreducible, but not prime: $k[C]/(x)=k[y]/(y^2)$ is not a domain.
Comment: one line proof!!!

Semicubical parabola coordinate ring


Suprimindo valor ao chamar função Javascript

Question: O código abaixo não passa um valor para y  mas mesmo assim o código funciona, alguém sabe como funciona?
Gostaria de aprender mais sobre, alguém sabe o nome desta característica do javascript?

function base(x) {
  return function produto(y) {
    return x * y;
  }
}

var f = base(2);
var g = base(-1);

console.log(f(2) + g(-1)); // 5
Answer: Esse conceito é o que se chama high-order-function. Ou seja uma função que retorna outra, configurada para um dado processo.
Programar dessa maneira integra-se na filosofia de functional programming, porque nesse caso a função base é pura e retorna sempre uma função, é portanto um instrumento do fluxo da aplicação.
Nesse caso quando invocas a função base recebes uma função high-order que recebe um argumento e multiplica pelo que já foi pré-configurado.
Nesse caso podias até ter nomes mais claros como:

function base(x){
    return function produto(y){
           return x * y;
    }
}

var vezesDois = base(2);
var inverterSinal = base(-1);

console.log(vezesDois(7)); // 14
console.log(inverterSinal(435)); // -435


Pegar valor $_GET com url amigável

Question: Tenho a seguinte situação, quando a URL está sem valores depois da barra http://www.meusite.com/ e eu digito algo na busca http://www.meusite.com/?s=teste inclui minha página de resultado, agora quando a URL tem valores http://www.meusite.com/minha-pagina/?s=teste não inclui minha página de resultados, como eu poderia arrumar isso?
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1

$dir = "views/arch";
if (isset($_GET['url'])) :
    $url = addslashes($_GET['url']);
    $sep = explode('/', $url);
endif;

$pg = array('contato');
if (isset($_GET['s'])) :
    require_once (''.$dir.'/search.php');
elseif (isset($sep[0]) && $sep[0] == 'filter') :
    require_once (''.$dir.'/filtro.php');
elseif (isset($sep[1])) :
    require_once (''.$dir.'/categoria.php');
elseif (isset($sep[0]) && in_array($sep[0], $pg)) :
    require_once (''.$dir.'/'.$sep[0].'.php');
else :
    require_once (''.$dir.'/home.php');
endif;

Comment: Relacionado: [URL amigável, como fazer funcionar com HTACCESS](https://pt.stackoverflow.com/q/53973/3774)
Comment: Relacionado: [Passando variáveis pela URL utilizando URL amigáveis via GET](https://pt.stackoverflow.com/q/27534/3774)
Comment: Relacionado: [Duvida sobre htaccess](https://pt.stackoverflow.com/q/277086/3774)
Answer: tentou manipular os diretórios no .htaccess? Eu já precisei da seguinte situação:
<IfModule mod_rewrite.c>
 RewriteEngine On

 RewriteRule ^/?([A-Za-z0-9-]+)?$ arquivo.php?busca=$1 [NC,L]

 RewriteRule ^/?([A-Za-z0-9-]+)?/$ arquivo.php?busca=$1 [NC,L]

 RewriteRule ^/?([A-Za-z0-9-]+)?/([^/.]+)/$ arquivo.php?url=$1&busca=$2[NC,L]

</IfModule>

Dessa forma, eu determinei exatamente a $_GET['busca'] quando está na raiz ou quando está em outro nível.
Atualizando
Quando você envia a variável na raiz do diretório, não precisa do .htaccess para recuperá-lo.
Ao tentar recuperar pelo .htaccess, você utiliza um parâmetro da própria URL para recuperar. Exemplo abaixo:
.htaccess
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule ^/?([A-Za-z0-9-]+)/?([A-Za-z0-9-]+)/?$ index.php?url=$1&s=$2 [NC,L]

</IfModule>

index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo 'Minha query de busca:'.$_GET['s'].'
';
echo 'Meu diretório:'.$_GET['url'].'
';

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

//QUEBRANDO E EXIBINDO OS FRAGMENTOS DA URL APÓS ?
var_dump(explode("?", curPageURL()));

?>

Como pode ver no arquivo, adicionei também uma função caso queira, por algum motivo, coletar a query da URL da forma tradicional também (não amigável como seu exemplo).
Você pode ver o resultado compilado aqui: https://www.crm.ecowd.inf.br/teste/a/c/?search=abc
Espero que tenha ficado mais claro, abraços e boa sorte
Comment: @goio, complementei a resposta com um exemplo e acho que o maior problema era a transformação de query em parâmetro pelo .htaccess; espero que ajude irmão, abs
Comment: No segundo nível, não precisa ter o Rewrite Rule com e sem barra? Adicionei a linha:

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f

RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1

RewriteRule ^/?([A-Za-z0-9-]+)?$ index.php?s=$1 [NC,L]

RewriteRule ^/?([A-Za-z0-9-]+)?/$ index.php?s=$1 [NC,L]

RewriteRule ^/?([A-Za-z0-9-]+)?/([^/.]+)$ index.php?url=$1&s=$2 [NC,L]

RewriteRule ^/?([A-Za-z0-9-]+)?/([^/.]+)/$ index.php?url=$1&s=$2 [NC,L]
Comment: Não vai velho `
 RewriteEngine On
 RewriteCond %{SCRIPT_FILENAME} !-f
 RewriteCond %{SCRIPT_FILENAME} !-d
 RewriteRule ^(.*)$ index.php?url=$1
 RewriteRule ^/?([A-Za-z0-9-]+)?$ index.php?s=$1 [NC,L]
 RewriteRule ^/?([A-Za-z0-9-]+)?/$ index.php?s=$1 [NC,L]
 RewriteRule ^/?([A-Za-z0-9-]+)?/([^/.]+)$ index.php?url=$1&s=$2 [NC,L]
 RewriteRule ^/?([A-Za-z0-9-]+)?/([^/.]+)/$ index.php?url=$1&s=$2 [NC,L]
`

Pegar valor $_GET com url amigável


Name or service not known when try to send email with flask-mail

Question: Hello I have the following configuration in the thunderbird:

And I set this configuration inside app with:
app.config["MAIL_SERVER"] = "smtp....."
app.config["MAIL_PORT"] = 587
app.config["MAIL_USERNAME"] = "info@...."
app.config["MAIL_PASSWORD"] = "pasword"
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USE_SSL"] = False

but when I try to send an email with
from flask_mail import Message, Mail

mail = Mail(app)

msg = Message(
    "Hello", sender="info@....", recipients=["email@example.com"]
)
try:
    mail.send(msg)
except Exception as e:
    print("---------")
    print(e)

I got the following error:
[Errno -2] Name or service not known

how can I solve it?
Thanks
Answer: The app.config["MAIL_SERVER"] configuration was wrong.


404 blog url's delivering 403 status

Question: I have a blog set up on my site, when I visit a page it delivers a 200 as it should, however when I visit a page that should not be there, it delivers a 403.
Example:
domain.com/blog/good-url/ = 200
domain.com/blog/bad-url/ = 403
The second example should be delivering a 404, any ideas where this could be coming from?
Comment: Did you ever change the default 404 page? You could have accidentally set it to a page that is not available to anonymous users. Have you updated your htaccess with any 404 page rules? Check that all 404 pages are accessible to anon users.
Comment: Thanks Chris, The 404 page works for other URL's that are not in the /blog/ directory. So the 404 page works & is properly set.
Answer: After looking at the source code of the blog module, it appears that the path /blog/<somestring> is sort of reserved for the blog module itself.
Problem:
The pattern based aliases created when creating a new blog node seem to take precedence over those internal paths so if your URL alias pattern is blog/[node:title], you are shown the expected blog node as long as it exists.
Once the blog node is deleted and the alias is deleted with it, /blog/<somestring> means "do whatever path <somestring> does in the blog module" which results in a 403 Forbidden error rather than the expected 404 Not Found error.
Solution:
The only solution I found is to use a different URL alias pattern such as blogs/[node:title] which avoids the problem.
Tip:
Use the Redirect module to let the Pathauto module create redirects when changing URL aliases. It also helps to keep track of those redirects so you can see which redirect URLs still receive traffic and which could be deleted.

404 blog url's delivering 403 status


Statistical measures for data validation

Question: I have to validate the data in one database by comparing it to data from a validated application system. The solution I came up with was (at least in theory) creating a statistical method that would define the number of random samples needed to check on a table of the database, in order to say, that with a 95% chance the number of errors is representative for that table. Then, with the probability of the errors I could consider if the data is valid or not.
The binomial distribution doesn't help, since I don't have any knowledge about the probability at which an error could be found. My statistical knowledge is pretty rusty and I can't figure it out right now.
Just to clarify again:
Given N the number of entries in a table I want to know what number n for random samples I have to chose in order to be able to say after testing, that the probability of the error is p, at a 95% accurateness.
I would be very helpful for every helping idea I could get. Any references to literature or sites covering this would also be greatly appreciated. Thanks in advance!
Answer: You could work out (using the binomial distribution) the minimum sample size for which observing no errors will allow you to conclude that $p$ is less than a stipulated critical value $p_\mathrm{c}$ with 95% confidence. (It's approximately $\frac{3}{p_\mathrm{c}}$; see the Rule of Three) In any case a small trial study would give you an estimate of $p$ to use in deciding the sample size for a larger study. If the sample size looks like a large-ish fraction of the total no. records then use the hypergeometric distribution rather than the binomial. You might also need to consider whether the errors are independent, if you want to extend inference beyond the current version of this particular table.


Has my Apache server been exploited?

Question: I recently got the following in my server logs:
70.190.xxx.xx - - [26/Sep/2010:19:03:17 -0500] "\xdcm5\xa1\x1a\xec\xa2\x7f\xc2\xab\x83<\xb5\xa3h\xb1^B\x88\x19K\xa5C\xcf\x15\x1a\xc1\x84\xe4\x8a]c\xdd\xe0\xc2e\x9f\x7f;M\xa0P\xfb\x8bo\xf6\xcb\x12\xdaq\x81\xb7\xf6\xe3N\xb5\x04`\"\\xcc" 200 4581 "-" "-"
and
70.190.xxx.xx - - [26/Sep/2010:19:10:54 -0500] "&\x9a\x18\x02\xef@2s;\xff\xea\x84" 200 4582 "-" "-"
Normally I wouldn't be concerned because I do get a lot of junk randomly hitting my server, but I've never seen anything like this one and the server is returning 200.
Comment: Out of curiosity, what does your server return when this URL is requested?  You may need to use telnet and submit the HTTP 1.1 GET yourself since I think most browsers will "correct" such a URL.
Comment: Possible duplicate of [How do I deal with a compromised server?](https://serverfault.com/questions/218005/how-do-i-deal-with-a-compromised-server)
Answer: That doesn't by itself indicate that your machine is compromised.  It just means that someone is probably trying to exploit a buffer overrun in your webserver.
The fact that your server is returning 200 is interesting, but not conclusive.

Has my Apache server been exploited?


Which of the statements are correct

Question: I was trying to answer the question below.
Given the sets S1 = {2,3,5,8,9} and S2 = {3,4,5,6,7} which of the following statements are correct?
a. Median value and mean are 5 for both sets
b. For S2 the median value is equal to the mean value
c. S1 has a larger variance than S2
d. Both sets have the same variance
I tried solving it and it seems like both b and c are correct. The problem is there can only be one correct answer. Can someone check to see if they can answer the question or tell me if there is an error in the question.
Comment: You are correct, both b,c are correct. I got $E[S_1]=5.4,E[S_2]=5=\text{median}(S_2),V[S_1]=7.44,V[S_2]=2$. Probably question has error.
Comment: "...[W]hich of the following statements are correct?" does not seem to limit you to choosing _one_ correct answer.
Comment: Why don't you write what you think the appropriate sizes for the sets are?
Answer: You need to start by finding means, medians, and variances of the two samples.
I have done this using R.
<code>S1 = c(2,3,5,8,9)
summary(S1); var(S1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    2.0     3.0     5.0     5.4     8.0     9.0
[1] 9.3

S2 = c(3,4,5,6,7)
summary(S2); var(S2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
      3       4       5       5       6       7
[1] 2.5
</code>
Answer: Contrary to your thinking, "which of the following statements are correct" allows several true statements.

Which of the statements are correct


Natural deduction Proof [(p →r) ∨ (q→r)]

Question: Trying to go from [(p →r) ∨ (q→r)] to prove (p∧q)→r.
Wanted to know if I am heading in the right direction with my deductions or where I am getting messed up.

(p→r) ∨ (q→r) premise
p assumption
p→r assumption
r →elim 2,3
q assumption
q→r assumption
r →elim 5,6
p∧q ∧intro 2,5
(p∧q)→r →intro 3-4,6-7,8
Comment: Try to use $p\implies q \Leftrightarrow \neg p \vee q$. I am nota sure about 8.
Answer:
Wanted to know if I am heading in the right direction with my deductions or where I am getting messed up.

You are not.  $p\wedge q$ should not be derived from assumptions of $p$ and $q$, it should be the assumption.
Always keep an eye on the goal.
You wish to prove $(p\wedge q)\to r$ from the premise $(p\to r)\vee (q\to r)$.
Therefore assume $p\wedge q$ aiming to derive $r$.  To derive that, use a proof by cases.
$\begin{array}{|l}(p\to r)\vee(q\to r)\\\hline\begin{array}{|l} p\wedge q\\\hline\begin{array}{|l}p\to r\\\hline\vdots\\ r\end{array}\\\begin{array}{|l}q\to r\\\hline\vdots\\r \end{array}\\r\end{array}\\(p\wedge q)\to r\end{array}$
Comment: So utilizing a proof by cases it would look something more like this?
$\begin{array}{|l}(p\to r)\vee(q\to r)\\\hline\begin{array}{|l} p\wedge q \quad     assumption\\\hline\begin{array}{|l}p\to r \quad assumption\\\hline p \quad \wedge elim 2\\r\quad \to elim3,4\end{array}\\\begin{array}{|l}q\to r \quad assumption\\\hline q \quad \wedge elim 2\\r \quad \to elim 6,7\end{array}\\r\end{array}\\(p\wedge q)\to r \quad \to intro 2-9\end{array}$
Comment: Yes, indeed. @AndrewRyan
Comment: So these are the right steps? what would be the logic then for deducing line 9?
Comment: $\vee$ elimination (1, 3-5, 6-8).
Comment: What would be a good resource to learn more about the proof by cases?


Como não acumular efeitos em Hide e Show

Question: Clicando no botão Fade a div some e em seguida clicando no botão UnFade a div reaparece. Até ai tudo bem.
Se em seguida clicar de novo no botão Fade, a div desaparece, aparece e desaparece de novo.
Se em seguida clicar no botão UnFade, a div aparece, desaparece e aparece de novo.
Se em seguida clicar de novo em fade, a div desaparece, aparece, desaparece, aparece e desaparece novamente.
Então se você clicar alternadamente 10 vezes em Fade e UnFade vai ver que a div  vai e volta 10 vezes. Gostaria de saber se tem jeito de evitar isso. Se clicar em fade desaparece e em Unfade aparece independentemente do número de vezes que foram clicados alternadamente.

function functionHide() {
  $("div").hide(1000);
}
function functionShow() {
  $("div").show(1000);
}

$( "#id1" ).click(function() {
  $( "body" ).click(functionHide);
});

$( "#id2" ).click(function() {
  $( "body" ).click (functionShow);
});

<button id="id1">Fade</button>
<button id="id2">UnFade</button>

Click!

Comment: É um pouco difícil tentar perceber o que precisas realmente. Já experimentaste adicionar um monitor de eventos ?
Answer: O $("body").click(...) no seu código não faz sentido, principalmente estando dentro de outro click.
O que seu código estava fazendo era, cada vez que se clicava no botão, você apendava um novo event handler ao elemento body, que ia ser executado quando o body fosse clicado. Por isso a cada clique a ação era executada uma vez mais, pois os event handlers iam sendo adicionandos e os antigos continuavam lá.
$(document).ready(function() {
  function functionHide() {
    $("div").hide(1000);
  }
  function functionShow() {
    $("div").show(1000);
  }

  $( "#id1" ).click(functionHide);

  $( "#id2" ).click(functionShow);
})

Comment: Acho que minha explicação está clara, faça o que está dito executando o código que vais perceber o que ocorre. Se clicar em fade a div some. Clique em UnFade ele aparece. Clique em Fade a div some, aparece e some. Isso que quero bloquear.  Com relação ao seu código não consegui fazer NEM funcionar.
Comment: Se NEM funcionou é porque, no seu HTML, você está adicionado o script antes de ter adicionando os botões, aí na hora que ele executar não vai encontrar os botões, pois eles não existem ainda.
Ou você inclui o javascript depois dos elementos, ou engloba todo o código javascript dentro de um $(document).ready().
Vou atualizar a resposta com essa segunda opção, pra ficar mais claro. Faça o que está dito que vais perceber que funciona.
Comment: Valeu, é isso mesmo! Esqueci desse detalhe.
Answer: Já visualizei seu problema amigo.
function functionHide() {
    $("div").hide(1000);
}

function functionShow() {
    $("div").show(1000);
}

A declaração das funções acima estão ok. O problema é como você está fazendo para chama-las.
Pelo que entendi, você tem um botão que ao clicar, você esconde algo ou exibe, através das funções previamente declaradas.
Logo ficaria simplesmente assim:
$("#id1").click(function() {
    functionHide();
});

$("#id2").click(function() {
    functionShow();
});

Seu erro foi tentar complicar a chamada das funções utilizando um $("body").click() que não tem nenhuma finalidade dentro da sua necessidade.

function functionHide() {
  $("div").hide(1000);
}
function functionShow() {
  $("div").show(1000);
}

$("#id1").click(function() {
    functionHide();
});

$("#id2").click(function() {
    functionShow();
});

<button id="id1">Fade</button>
<button id="id2">UnFade</button>

Click!

Comment: Beleza, funcionou legal. Porque o script tem que ficar depois dos botões pra que funcione?
Comment: Não necessariamente. A ordem que deve ser respeitada é a inclusão do script do Jquery e em seguida seus comandos de programação.


What is the Probability of Choosing 3 Specific Balls from a 15-Ball Set?

Question: My high school geometry textbook includes the following problem as an example:

Three pool balls are chosen at random from a set numbered from 1 to 15.  What is the probability that the pool balls chosen are numbered 5, 7, and 9?

My answer is $\frac{1}{455}$.  The text book's answer is $\frac{6}{455}$.  Which answer is correct?
I arrive at my answer, as follows:

The probability of the desired result is the ratio of the number of outcomes that yield the desired result to the total number of possible outcomes.
The desired result, balls 5, 7 and 9, together form a single 3-ball combination; a single outcome:
$$
1
$$
The total number of possible 3-ball combinations is:
$$
\frac{15!}{3!(15-3)!} = \frac{(15 \cdot 14 \cdot 13)}{6} = \frac{2730}{6} = 455
$$
Thus, the ratio described in (1), above, is $1\colon455$, and the answer is:
$$
\frac{1}{455}
$$

There are at least two alternative approaches that yield the same answer:

Rather than using combinations, one might use permutations, in which case the numerator is the $3!$ permutations that yield the desired result, and the denominator  is the $\frac{15!}{(15-3)!}$ permutations that could occur in choosing 3 balls, which is equal to $\frac{6}{2730}$ = $\frac{1}{455}$.
Or, one could use the product of the odds of each selection being a success:  $\frac{3}{15} \cdot \frac{2}{14} \cdot \frac{1}{13}$ = $\frac{6}{2730}$ = $\frac{1}{455}$.

HOWEVER, my textbook says the solution is:
$$
\frac{3!}{\frac{15!}{3!(15 - 3)!}} = \frac{6}{455}
$$
The textbook's statement of the problem and solution is here:
Lesson 13-3, Permutations and Combinations: Problem 6.  I believe the textbook's solution compares a number of permutations in the numerator to a number of combinations in the denominator, which seems to me to be a matter of apples and oranges.
Comment: Welcome to MathSE.  You are correct.  Please notify the publisher about the error.
Comment: Yes, one possibility works among the $\binom {15}3=455$, the probability is $1/455$.
Comment: @N.F.Taussig, thank you for the kind welcome.  This looks like the right place for someone who enjoys math.
Answer: Your answer is correct.
 We have to consider either permutation or combination for both numerator and denominator  to get the correct probability.
Comment: I appreciate you taking the time to provide an answer. Thanks.


On the cardinality of a finite extension's Galois group

Question: As part of a proof, my textbook1 essentially asserts (without proof, AFAICT) that if $L:K$ is a finite extension, and $\mathrm{Gal}(L:K)$ is the Galois group of $L$ over $K$, then $\left| \mathrm{Gal}(L:K) \right|$ (i.e. the cardinality of this Galois group) is finite.
I don't see how this follows from the results derived up to this point in the book.  All the theorems that would say something about the cardinality of $\left| \mathrm{Gal}(L:K) \right|$ make assumptions that do not hold above.  (For example, corollary 7.29, on p. 117, states that $\left| \mathrm{Gal}(L:K) \right| = [L:K]$, provided that $L$ is both normal and separable.)

EDIT:  To avoid misunderstandings, here are the definitions my book uses (copied verbatim, from p. 94):

Let $L$ be an extension of a field $K$.  An automorphism $\alpha$ of $L$ is called a $K$-automorphism if $\alpha(x) = x$ for every $x$ in $K$.  The set of all $K$-automorphisms of $L$ is denoted by $\mathrm{Gal}(L:K)$.

EDIT 2: An additional source of confusion for me is the statement of Theorem 7.12 (on p. 100, well before the assertion cited above):

Theorem 7.12
Let $L$ be a finite extension of a field $K$ and let $G$ be a finite subgroup of $\mathrm{Gal}(L:K)$.  Then $[L:\Phi(G)] = \left| G \right|$.

...where the map $\Phi$ is defined (on p. 95) as
$$
\Phi(G) = \{x \in L | \alpha(x) = x , \; \forall \alpha \in G \}
$$
To be more specific, my confusion stems in part from the fact that the statement of the theorem bothers to specify that the subgroup $G$ is finite.  This seems strange if $\mathrm{Gal}(L:K)$ (which contains $G$) is finite to begin with.
(On top of everything, right before proving Theorem 7.12, the author points out that "[t]he proof is longer than one might have expected -- or hoped".  This makes me wonder if these seemingly obvious cardinality facts are actually pretty hard to prove rigorously.)

1 John M. Howie, Fields and Galois Theory, p. 117.
Comment: $L$ is a finite dimensional $K$-vector space. An automorphism of $L$ that fixes $K$ is in particular a $K$-linear transformation. A linear transformation is determined once you fix its values at a basis. But in addition to being linear an element of the basis can only be sent to one of the finitely many roots of its minimal polynomial over $K$. So, finitely many choices.
Comment: @kjo An element $e\in L$, if $L:K$ is a finite extension, must satisfy a polynomial with coefficients in $K$. This is because otherwise $1,e,e^2,...$ would be linearly independent over $K$ contradicting that $L$ is a finite-dimensional vector space over $K$. Among all polynomials with coefficients in $K$ that $e$ satisfies, there is a monic one with minimal degree. That is the (it is unique by Euclid's algorithm) minimal polynomial. Each element of your basis of $L$ over $K$ satisfies one such polynomial.
Comment: @TorstenSchoeneberg: not in this book.  Since this could be a source of confusion, I'll edit my post to include the definitions I'm using.  Give me a few minutes.
Comment: @TorstenSchoeneberg: beyond the trivial assertion $\mathrm{Gal}(L:K) \subseteq \mathrm{Aut}(L)$, I don't know what else to say about the general case you cite.
Comment: @SphericalTriangle: wait, what minimal polynomial now?
Comment: @SphericalTriangle: OK, I see it now.  Thank you!  I'd be happy to accept your comment as the answer to my question if you care to post it as such.
Comment: @SphericalTriangle: I thought I'd be able to fill in the details of your argument, but I can't.  Please, don't spend any more time on this question.  I think I will have to post a vastly more detailed version of my original question, spelling out in full detail what can be assumed, etc.  Sorry for my flip-flopping...
Comment: @SphericalTriangle: I just needed a good night's sleep; when I woke up this morning, I was able to fill in the details of your argument (I think).  I posted them as an answer.  Please let me know if I got them right.  (Still, I find it a bit surprising that the book's author would have omitted such a substantial argument.)
Answer: This is my best attempt to fill in the details of the answer that SphericalTriangle sketched in his/her comments.
Since $L:K$ is a finite extension, there is a finite basis $\{1,z_1,z_2,\dots,z_n\}$ of $L$ over $K$, with all the $z_i$ in $L\backslash K$.  Each $z_i$ is therefore the root of a corresponding minimal polynomial $m_i \in K[X]$.
(Otherwise, if some $z_k$ was not the root of any polynomial in $K[X]$, the infinite set $\{1, z_k, z_k^2, \dots \}\subseteq L$ of non-negative powers of $z_k$ would be linearly independent, thereby contradicting the finiteness of $[L:K]$.)
For each $i \in \{1,\dots,n\}$, let $d_i$ be the degree of $m_i$, let $\{\zeta_{i,1},\zeta_{i,2},\dots,\zeta_{i,d_i}\}$ be its roots, and, without loss of generality, assume that $\zeta_{i,1} = z_i$.
For any $K$-automorphism $\varphi$ of $L$, specifying the value of $\varphi$ at the basis elements $\{1,z_1,z_2,\dots,z_n\} = \{1, \zeta_{1,1}, \zeta_{2,1}, \dots, \zeta_{n,1}\}$ fully determines $\varphi$.
By virtue of being a $K$-automorphism, $\varphi$ must (a) fix $1$, and (b) map each root $\zeta_{i,1} = z_i$ of $m_i$ to some other root $\zeta_{i,j}$ of $m_i$.  (In more detail: $\forall a \in L, \varphi(m_i(a)) = m_i(\varphi(a))$, because $\varphi$ is an automorphism of $L$ that fixes the coefficients of $m_i \in K[X]$.  Hence, $m_i(\varphi(\zeta_{i,1})) = \varphi(m_i(\zeta_{i,1})) = \varphi(0) = 0,$ which means that $\varphi(\zeta_{i,1})$ is a root of $m_i$, so it must equal $\zeta_{i,j}$, for some $j$.)
Since there are at most $d_i$ distinct values that each $z_i$ can be mapped to by a $K$-automorphism of $L$ (i.e. by an element of $\mathrm{Gal}(L:K)$), there can be at most $\prod_1^n d_i < \infty$ distinct $K$-automorphisms of $L$.  Hence $\mathrm{Gal}(L:K)$ is finite.
Comment: That's all. The reason why it must send $\zeta_{i,1}$ to some root of $m_i$, which you probably know, is because if $m_i(x)=\sum_j k_jx^j$ for $k_j\in K$. Then $0=\phi(0)=\phi(m_i(\zeta_{i,q}))=\sum_j k_j\phi(\zeta_{i,1})^j=m_i(\phi(\zeta_{i,1}))$.


Delphi TDockZone resizing with rsUpdate style

Question: I use TPanels for docking in my project, where I can dock more forms into.
But the docking zones resize only with "rsPattern" style.
I want them to resize in the "rsUpdate" style.
Because Controls.TDockTree unfortunately has all necessary routines private (not allowing to change this in any TDockTree descendant - because TDockZone.FOrientation is only private etc.), I made custom copy of Controls.pas for my project and modified that code directly.
That way is sufficient for me because it works as expected but with each Delphi upgrade I have to change this code again, for new Controls.pas (when it would change).
Is there some cleaner way (of course without using external libraries)? Or how do you solve such problems?
Comment: You can use class helper to access private fields..
Comment: Just prefix it with "Self" in the method implementation in you class helper.
Comment: Works perfectly, thank you!
Answer: This solution is based on useful hint of ZENsan and extends CaptionedDockTree.pas (tested in Delphi XE):
<code>type
  TDockZoneHelper = class helper for TDockZone
  private
    function GetOrientation: TDockOrientation;
    function GetParentZone: TDockZone;
  public
    property ParentZone: TDockZone read GetParentZone;
    property Orientation: TDockOrientation read GetOrientation;
  end;

  TDockTreeHelper = class helper for TDockTree
  private
    function GetBorderWidth: Integer;
  protected
    procedure HlpForEachAt(Zone: TDockZone; Proc: TForEachZoneProc);
    function HlpInternalHitTest(const MousePos: TPoint; out HTFlag: Integer): TDockZone;
    procedure HlpSetNewBounds(Zone: TDockZone);
    procedure HlpUpdateZone(Zone: TDockZone);
  public
    property BorderWidth: Integer read GetBorderWidth;
  end;

{ TDockZoneHelper }

function TDockZoneHelper.GetOrientation: TDockOrientation;
begin
  Result := Self.FOrientation;
end;

function TDockZoneHelper.GetParentZone: TDockZone;
begin
  Result := Self.FParentZone;
end;

{ TDockTreeHelper }

procedure TDockTreeHelper.HlpForEachAt(Zone: TDockZone; Proc: TForEachZoneProc);
begin
  Self.ForEachAt(Zone, Proc);
end;

function TDockTreeHelper.GetBorderWidth: Integer;
begin
  Result := Self.FBorderWidth;
end;

function TDockTreeHelper.HlpInternalHitTest(const MousePos: TPoint;
  out HTFlag: Integer): TDockZone;
begin
  Result := Self.InternalHitTest(MousePos, HTFlag);
end;

procedure TDockTreeHelper.HlpSetNewBounds(Zone: TDockZone);
begin
  Self.SetNewBounds(Zone);
end;

procedure TDockTreeHelper.HlpUpdateZone(Zone: TDockZone);
begin
  Self.UpdateZone(Zone);
end;

{ TMyCaptionedDockTree additions }

procedure TMyCaptionedDockTree.MouseDown(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer; var Handled: Boolean);
var
  Zone: TDockZone;
  Flag: Integer;
begin
  FSizingZone := nil;
  if (Button = mbLeft) and not (ssDouble in Shift) then
  begin
    FSizingPoint := Point(X, Y);
    Zone := HlpInternalHitTest(FSizingPoint, Flag);
    if Flag = HTBORDER then
      FSizingZone := Zone;
    else
      inherited;
  end else
    inherited;
end;

procedure TMyCaptionedDockTree.MouseMove(Shift: TShiftState; X, Y: Integer;
  var Handled: Boolean);
begin
  if FSizingZone <> nil then
  begin
    FSizingPoint := Point(X, Y);
    if FSizingZone.ParentZone.Orientation = doHorizontal then
      FSizingZone.ZoneLimit := FSizingPoint.y + (BorderWidth div 2)
    else
      FSizingZone.ZoneLimit := FSizingPoint.x + (BorderWidth div 2);
    HlpSetNewBounds(FSizingZone.ParentZone);
    HlpForEachAt(FSizingZone.ParentZone, HlpUpdateZone);
  end else
    inherited;
end;

procedure TMyCaptionedDockTree.MouseUp(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer; var Handled: Boolean);
begin
  inherited;
  FSizingZone := nil;
end;
</code>


SocketIO + PhantomJS emit not working

Question: I am having a pretty specific problem but I hope people can point me in the right direction for how to debug or even fix it. I am trying to write a local client which can run and test a webpage I had built which uses SocketIO.
I am running Phantom with the command line option --web-security=false since otherwise no in or out connections are legal as my local tester is not considered part of the same origin as my website I am testing (had to fix that before the listening would work).
Using PhantomJS I can't get the emit function from SocketIO to work. It just fails silently without any error. I know the socket is validly connected because it can listen to incoming events just fine (so the on() method works). I can run the same emitting code in a web browser and it works just fine.
Does anyone know alternatives to emit(), what lower level things emit() invokes that maybe I could patch, or how I should test things next? Any help is appreciated.
Comment: Related: http://stackoverflow.com/q/15725236/1816580 There is a life sign for PhantomJS 2 on github.
Comment: Also found this now, came back here to share the link for fellow googlers :) https://github.com/socketio/socket.io/issues/1746
Answer: After a lot of research it looks like this form of sockets simply aren't yet supported in phantomjs.  When the new 2.0 releases they are supposed to be but until then other options are better.  I tried to find a shim for a while but was unsuccessful.
In the end, I instead used node.js to run the main script, make the socket connections and then used the phantomjs node module to do the browser interactions rather than running the script as a pure phantom script.  This meant that the api interaction logic got pushed to the node application and the phantom code was just about interacting with the page but I was able to achieve the testing goal this way so I count it as success.

SocketIO + PhantomJS emit not working


Select relacionado a outro select, puxando dados do banco

Question: Necessito criar um formulário que puxa as opções do banco sql. Até aí tudo bem, eu fiz um while dentro de uma consulta em php;
<code>echo '<SELECT NAME = "setor">';
    while ( $temp = $setores->fetch_assoc() ) {
        echo '<OPTION>'.$temp['nome'];
    }
echo '</SELECT>';
</code>
Porém preciso que um segundo select só apresente as informações de acordo com a opção selecionada no primeiro select.
Então por exemplo, se neste select o usuário selecionar ''filmes'', o proximo select deve exibir os filmes existentes no banco, se ele selecionar ''series'', ele retorna as series registradas, e assim por diante.
Qual a forma mais simples em que eu poderia fazer isso?
Comment: O projeto tem JQuery ou só javascript?
Answer: No evento onChange do seu select, crie um método e faça uma busca em ajax para popular o segundo select.
Algo parecido com isso:
<code>$('.select1').on('change', function(){

    var id = $(this).val();

    $.ajax({
        url: 'url',
        data: {
            id: id
        },
        type: 'GET',
        dataType: 'json',
        success: function(data){

            var html = '';

            $.each(data, function(){
                html += "<option value='"+this.id+"'>"+this.texto+"</option>";
            });

            $('.select2').html(html);
        }
    })

})
</code>
Lembrando que no PHP você deve retornar um json para o JS:

echo json_encode($arrRetorno);