How can I enable, scan, and disable windows defender from inside a scheduled task?

Question: If windows defender is disabled can you later (through a script) enable, run a scan and then disable it via a powershell script that is invoked as part of the scheduler?
If this is possible then figuring out a way to email problems will be the next hurdle.
This is within a windows 2016 server environment.
Answer: Yes this should be possible with powershell on Windows Server 2016.
Commands obtained from technet (https://technet.microsoft.com/en-us/library/dn433280(v=wps.630).aspx)
Please see the below.
<code>Set-MpPreference -DisableRealtimeMonitoring $false
Start-MpScan -ScanType FullScan
$Report = Get-MpThreat | ConvertTo-Html
If ($Report -ne $null){
    Send-MailMessage -From <SenderAddress> -to <RecipientAddress> -SmtpServer <SMTPServer> -Subject "Defender Report" -Body $Report
}
Set-MpPreference -DisableRealtimeMonitoring $true
</code>
I can confirm that the scan works and the real time monitoring gets disabled, however as my WS2016 environment is clean I am unable to test the report.
This can be saved as a ps1 file and used in task scheduler.
Things that could have an impact is other anti-virus suites disable and prevent defender from being enabled, eset being an example.
hopefully this helps.
Comment: Thanks CraftyB. I will test this and get back to you.


What keys contain both E and Am and is there an easy trick to determine this?

Question: By 'keys contain' I mean in the normal rules of choosing what chords 'fit' within a given key, since of course you can put just about any chord anywhere if you try hard enough!
Is there a shortcut where you can take any major or minor chord and list the keys this chord could belong to, then narrow it down to keys containing two chords, etc?
Answer: "What keys contain both E and Am"... "By 'keys contain' I mean in the normal rules of choosing what chords 'fit' within a given key"
Strictly speaking, (perhaps surprisingly) the answer is: none. That is, if you only allow chords from the diatonic scales, without chromatic alteration, then there is no scale that contains both of these chords. Below, I will show you why this is, and what common alterations allow them both.

"...is there an easy trick to determine this?"
Absolutely! Just look at the Circle of Fifths. In the image below, I'm actually using a segment of the infinite Line of Fifths, since it works exactly the same, but will help you to pick the correct spelling for black keys.
This image works like a slide-rule. Beneath the line of fifths are two colored rows: the top for major keys, and the bottom for minor keys. Slide the colored part left or right, along the line of fifths, until the tonic column (I or i) lines up with the desired major/minor key. The roots of all other chords can now be read off the chart. Note that the orange chords (IV, I, and V) are major, the blue chords (ii, vi, and iii) are minor, and the funky yellow chord (vii°) is diminished.
If you're in the minor key (second colored row), the only things that change are the roman numerals associated with the chords (you add 2 or subtract 5), but the pattern of 3 majors, 3 minors, and a diminished stays the same. This gives you VI, III, and VII as major chords; iv, i, and v as minor chords; and ii° as a diminished.

As you can see, there's no way to slide it so that A is minor (blue) and E is major (orange). That means that in order to get both chords, we must chromatically alter one of them. We could pick a key containing an E minor chord, then alter it to be major, or we could pick a key with an A major chord, then alter it to be minor. (In the keys of D major/B minor, we'd have to alter both chords, since we'd have both an A major and an E minor).
However, there is an extremely common technique in the minor key, which is to raise the third of the v chord by a half step, which makes it a major chord (V). Note that the third of the v chord is also the seventh scale degree, so raising this note by a half step places it just under the tonic, creating a "leading tone" which wants to resolve to the tonic. This variant of the scale is called the Harmonic Minor. In the graph, this would be equivalent to replacing the blue "v" in the second row with an orange "V". In this case, you can see that you could have an A minor chord (i) and an E major chord (V) in the same scale: A harmonic minor.

Although the harmonic minor is an extremely common technique, it is not the only possible way to alter chords to get both E and Am together. By moving the colored portion around to different keys that contain both E and A, you can find what alterations are required to get them both. Here's some alternatives:

In C major, you'd be replacing iii with III, which causes it to act as a secondary dominant of vi (V/vi). This is quite common to do.
In G major, you'd be replacing vi with VI, which causes it to act as a secondary dominant of ii (V/ii). This is a bit less common.
In D major and D minor, you'd be replacing ii (or ii°) with II, which causes it to act as a secondary dominant of v (V/v). You'd also need to replace the V chord (which occurs naturally in D major, or in the altered D harmonic minor) with v. Making a dominant chord minor is a less common technique (at least in classical music), and it has the effect of weakening the sense of tonality, and increasing the sense of modality.
In E minor, you'd be replacing i with I (making the tonic a major chord), which might be used as a "Picardy Third" at the end of a piece, or to modulate to the parallel major.
In A major, you'd be replacing the I with a i (the reverse of the above) which can be used to modulate to the parallel minor.
In E major, you'd be replacing IV with iv. This minor subdominant tends to have a melancholy sound to it, and is good in chromatic passages leading up to a cadence. This is another common technique.
Comment: I'd add D major and D minor. In both case the E is on the IInd degree and serve as a secondary dominant to the Vth degree (namely, Am). Am is a minor dominant for Dm without the leading tone while Am in the key of D is an altered dominant.
Comment: Very nice answer. It may be helpful to clarify the statement "to raise the seventh scale degree in a v chord". I find that a lot of times people get confused when we talk about scale degrees in conjunction with chord tones and chord names (7 of V is 4 of the scale type of thing). It is clear to me what you mean but I think further clarification will prevent followup questions and provide more thorough understanding. As a not to the OP, the function of V in a minor key has a few implications that would probably be best asked in another question and likely has already been asked by someone else.
Comment: @Basstickler Good point! Better?
Comment: That is an excellent clarification!  I love the slide rule as well.  It spells out one of the things I would have included in my answer, which is that any given key (not modal) will have a naturally occurring 1/4/5 that are all major or minor (depending on being a major or minor key).
Comment: Does anyone know where a slide rule like this can be found online (not a physical version, just baked into a website), or a mobile app?
Comment: Great answer! Can you explan a bit more about "weakening the sense of tonality, and increasing the sense of modality". To me, major and minor are just other modes (ionian and aeolian), but I see people who see "modal" music something different to "major / minor". Can you elaborate on this duality? Thanks
Answer: Am and E are both found in the key of A minor.
The easiest way to find out what key the chords fit best is to figure out the relationship between the root of the chords. For example in this case E is a Perfect 5th away from A. In any key the dominant will be built a perfect 5th away from the tonic. In a minor key even though the dominant is naturally minor, it is very common to make it major to lead back to the tonic chord.
Comment: To add to Dom's answer, the term for changing the V chord in the fashion described above is called *musica ficta*.
Answer: I would say a good way to figure this out if you have two chords or any number of chords is to lay the notes out in alpha order. For Am and E this would look like this: Am (ACE) and E (EG#B) would be ABCEG#.
The next step is to determine which major or minor keys have those notes.
Here's another example, what key or keys fits best for the chords Am, Dm, Bb?
Am = ACE
Dm = DFA
Bb = BbDF
Lay them out in alpha order: A Bb C D E F
The only note we're missing is some sort of G. By looking at the notes, it seems we're in a flat key. We have Bb, which is the first flat in the order, therefore F major is a contender. Since we have an E and no Eb, we can have at most 1 flat, therefore F major is the only option.
In general, use your knowledge of key signatures to help you. Scales and chords go hand-in-hand.
Answer: I have an even faster way to do that, which doesn't even require a Circle of Fifths on hand:
Find the half-steps!
Simply put:

Take your chords, set of chords, or scales, and line up all of the notes into one big combined "scale". In this case, enharmonic spelling doesn't matter.
Look for any notes that are right next to each other.
Each half-step pair must be either Mi-Fa, or Ti-Do of a major key, because every major key (and any key in its modal family) has only two half-steps in it. Use those notes to find the key(s) that contain the notes!

(As others have noted, all solutions will in fact be adjacent keys on the Circle of Fifths.)

Examples:
In your case, we get [E G# A B C]. G# and A make a half-step, and B and C make a half-step as well. One possibility is that G#-A is Ti-Do. However, if A is Do, the C from the Am doesn't fit in the major key. So then we try B-C as Ti-Do (equivalent to checking G#-A as Mi-Fa). Problem is, there's no G# in C major. Since neither way works, we know that there cannot be any keys that contain both E major and A minor!
As another example: Let's try G major and A minor. We get: [G A B C D E]. There's only one half-step here (B-C), so we'll try C as Do. If C's the tonic, everything fits into C major! But we also have to try having C as Fa. If C is Fa, then G must be Do. After verifying that one as well, we now know that C major and G major must be the only keys that contain those two chords (and all keys in their respective modal families, which includes A minor and E minor)!
Lastly, we'll try Bsus4, Em, and D7: [B C D E F# G A]. B-C and F#-G make the two half-steps, so try G as Do. It works, so we know G major fits both chords. But try C as Do now, and there's a problem: the F# from our D7 chord is not in the key of C major. So G major is the only major key that can contain all three chords! (Again, E minor is included, as well as all other modes of G Ionian.)

Tips and Tricks
There's also a couple helpful tricks that can shortcut the process:

If there are more than two half-steps, then no key contains all the notes.
If there are more than 7 distinct notes, then no key contains all the notes.
If there are three or more notes a half-step apart, then no key contains all the notes.
If one of the chords is of the dominant seventh quality, the only key that can work is the one where the dominant chord is built on the 5th scale degree.
Augmented chords do not exist naturally in any key.
Diminished triads and half-diminished seventh chords may only be found on the leading tone (Ti) of the key.
Fully-diminished seventh chords do not exist naturally in any key.
Minor-major seventh chords do not exist naturally in any key.

Note, however, that there's a glaring flaw in this method: it doesn't account for harmonic minor. Harmonic minor is arguably more common in practice than strict natural minor or Aeolian, but because harmonic minor is not in the modal family of Ionian (major), the algorithm fails to recognize obvious solutions like E and Am being a part of A minor, or any other common usage of chords that strays from the purely diatonic instances.
It might be possible to develop a modified method where once you find Do, you check to see if the notes match a minor key as well as checking to see if it fits the major key on that tonic, or major augmented and then figuring out what minor key produces that particular Ionian #5 scale. A lot of the shortcut tricks I listed, though, don't hold when accounting for harmonic minor. For instance, no mode of Ionian contains any augmented, minor-major seventh, or fully-diminished seventh chords; however, all three chord qualities do arise organically from harmonic minor and its modes!
Comment: A similar trick can also be done with identifying keys from the tritone interval: If there is a tritone, the only possible key will use those notes as Fa-Ti *and* Ti-Fa. However, not as many collections of notes contain a tritone, and there will never be more than one tritone in a key. Thus if you do see a tritone, there is at *most* one key that fulfils the requirements.
Answer: The answer is no, because as you wrote:

By 'keys contain' I mean in the normal rules of choosing what chords 'fit' within a given key.

... what you are describing is the term "diatonic," which means only the notes that are contained within a key's signature.
A quick way to notice this is that the chord E major has the note G#, and the only keys that note can fit in, diatonically, are A, E, B, etc. (as well as their respective relative minors).  But none of these keys will diatonically allow C-natural, which is necessary for the A-minor chord! :)
Caleb's chart above is very helpful, BTW.
Answer: The example you have chosen, A minor and E major, don't break the rule, they rather reinforce a very common special case.   Those of us who were taught traditional harmony in the mid 20th century knew that the sure trick for differentiating between C major and A minor - both of them 'all white notes' by key signature - was to spot the sharpened 7th of the minor key.  The note that enables a full dominant chord, including the leading note, in a minor key.
Look for the diatonic notes, yes.   But also look for the note NOT in the key signature that defines the harmonic form of a minor scale.
Comment: That technique for differentiating the relative major and minor is far from foolproof.  Pieces in C major can have G#s in them too, especially if they are long enough to spend any time in the area of the relative minor.  A better technique is to look at the bass note at the end of the piece.
Comment: Yes, the G#s will tend to occur when the music is visiting A minor.   Music has (usually) a home key, but may travel to many others.
Answer: By asking what key includes a pair of chords, the answers are as previously given. However, there is more flexibility if you ask what scale contains a pair of chords. In that case, 02fentym's answer provides the mechanism.
Lay out the notes of your chords in alphabetical order, as indicated.
A B C E G#
Now you can construct a scale that suits your purposes.

The chromatic scale, of course, trivially contains all of those notes.
The A harmonic minor scale also contains those notes.
The ascending A melodic minor scale contains those notes.
The E "double harmonic" scale works: E F G# A B C D# E

For a complete list, try the "Musical Scale Search Tool", which allows you to enter notes and/or chords that your scale should contain, and it will provide the options. The tool includes options for the types of scales to give in the results.

Western diatonic scales
Greek modes
Altered Greek modes
Less common Western scales
Non-Western scales


Move validator message inside function

Question: I have a custom validator. I want to move the validator message inside the my_validator hook function.
$this->validate($request, [
            'package_name' => 'required',
            'package_version' => 'required|my_validator'
        ],
        [
            'my_validator' => 'Some custom message.'
        ]);

Answer: There are only two ways to add your validation message:

Using the $message array when using the validate function (as you've already done).
Adding your message to the resources/lang/en/validation.php lang file, as below:

return [
    // ...
    'my_validator' => 'Some custom message.',
    // ...
];

Move validator message inside function


Implicit differentiation and normal lines

Question: Find the y-coordinate of all points on the curve $2x + (y + 2)^2 = 0$ where the normal line to the curve passes through the point $(-9/2, -5)$ (not on the curve).
There appears to be $3$ y-coordinates and I'm not sure how to solve this. Can anyone give me a step-by-step walkthrough on how to do this?
Comment: Related: http://math.stackexchange.com/questions/540862/calculus-normal-line-to-curve-through-point-not-on-curve
Comment: This looks like a homework problem. If it is you should flag it as such. Also let us know what you have tried so far.
Answer: It suffice to differentiate and we find
$$2dx+2(y+2)dy=0$$
which implies $$\frac{dy}{dx}=-\frac{1}{y+2}$$
So the slope of the normal line should be inverted, and we have the equation to be $y-y_{0}=(y_{0}+2)(x-x_{0})$. If we let $y=-5$, $x=-9/2$, plug into the equation we have:
$$-5-y_{0}=(y_{0}+2)(-9/2-x_{0})$$as well as $$2x_{0}+(y_{0}+2)^{2}=0$$
The rearranged equation is a cubic since $x_{0}=\frac{1}{2}(y_{0}+2)^{2}$. I think that's where the 3 $y$ values coming from.
Answer: I'm picking up this old problem (and its "partner"), in part to correct some typos and mis-statements, and in part because it turns out to be less intimidating to solve exactly than it appears.
I'm going to call the external point $ \ (X, Y) \ , \ $ and $ \ (x_0, y_0) \  $ the point(s) we are interested in locating on the "horizontal parabola" $ \ -2x \ = \ (y+2)^2 \ $ [which has its vertex at $ \ ( 0, -2 ) \ $ and "opens to the left"] .  We'll use the already established fact that the slope of the normal line at $ \ (x_0, y_0) \ $ is $ \ m \ = \ y_0 + 2 \ $ to write the equation of any such normal line through the external point as
$$ \ y_0 - Y \ = \ (y_0 + 2) \ (x_0 - X) \ \ \Rightarrow \ \ y_0 - Y \ = \ (y_0 + 2) \ (\ [-\frac{1}{2}(y_0+2)^2] - X) \ \ , $$
correcting a "typo" in user32240's answer.  It is noted correctly that this leads to a cubic polynomial in $ \ y_0 \ $ of the type for which many of us have learned to salivate "Cardano!" on sight.
I will confess that I graphed the function first to see whether this looked like anything could be done without bringing in "heavier computational machinery".  As it happens, because of the choices of values in the two related problems, we can do something simpler.  If we re-write the left-hand side of the equation and rearrange terms, we obtain
$$ ( y_0 + 2 ) - ( Y + 2 ) \ =   \ -\frac{1}{2}(y_0+2)^3 \ - \ X \ (y_0 + 2) $$
$$ \Rightarrow \ \ -\frac{1}{2}(y_0+2)^3 \ - \ (X + 1) \ (y_0 + 2) \ + \ (Y + 2) \ = \ 0  \ \ .   $$
We'll multiply through by $ \ -2 \ $ to make this a monic polynomial and make the substitution $ \ u \ = \ y_0 \ + 2 \ $ to produce $ \ u^3 \ + \ 2 \ (X + 1) \ u \ - \ 2 \ (Y + 2) \ = \ 0  \ \ .   $
Now we'll set to work solving the problems for the given "external" points (I use quotes for a reason we'll see shortly).  For the other problem (#540862), we have $ \ (X, Y) \ = \ ( -27, -50 ) $ , for which the polynomial is $  \ u^3 \ - \ 52  u \ + \ 96 \ = \ 0 \ . $  A little work with the Rational Zeroes Theorem and synthetic division leads us to find one root is $ \ u = 2 \ $ , and the polynomial factors nicely as $ \ (u + 8) \ (u - 2) \ (u - 6) \ = \ 0 \ . $  The three points we seek are thus $ \ (-32 , -10 ) \ , \ (-2 , 0 ) \ , \ $ and $ \ (-18 , 4 ) \ . $ [This is also in response to a remark in njguliyev's answer for that problem: there is no "vertical" normal line to this "horizontal parabola"; all of the solutions come directly from the equation as it was found.]

[A property of the normal line through an external point perhaps worth mentioning is that we have incidentally found that  $ \ (-32 , -10 ) \ $ is the closest point on the parabola to $ \ (X, Y) $ $ = \ ( -27, -50 ) . $  In turn, it is the closest point on the parabola to any other point on the same side of the normal line.  I have said a bit about this topic here.]
As for the problem statement above, it is not entirely accurate, as the point $ \ (X, Y) \ = \ ( - \frac{9}{2}, -5 ) $ does in fact lie on the parabola.  However, this does not materially affect our calculations, and already "tips us off" as to what one of the solutions is (since a point on the curve automatically is on its normal line).  The cubic polynomial here is $  \ u^3 \ - \ 7  u \ + \ 6 \ = \ 0 \ , $ one of its roots again turns out to be $ \ u = 2 \ , $ and its factorization is $ \ (u + 3) \ (u - 1) \ (u - 2) \ = \ 0 \ . $ [OK, I happened to start off using 2 again: 1 is a more obvious root...]  The solution points are therefore $ \ (- \frac{9}{2} , -5 ) \ $ , $ \ (- \frac{1}{2} , -1 ) \ , \ \text{and} \ (-2 , 0 ) \ . $

I'm afraid I can't say that there is much of what I've done here that can be commended as a general method; things work out as tidily as they have largely because of the choices for the "external points".


When would a blocking call to flock fail?

Question: I was reading about flock. The example has this line:
flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
This call is a blocking call right? So if the lock is already taken the call blocks.
I assume that if the call returns the lock is granted. So when would the die would occur?
Answer: flock is a wrapper for the system call of the same name. $! is set by the system. So consult the system's documentation for your answer.
On my system, as per man 2 flock,

EBADF: fd is not an open file descriptor.
EINTR: While waiting to acquire a lock, the call was interrupted by delivery of a signal caught by a  handler;  see  signal(7).
EINVAL: operation is invalid.
ENOLCK: The kernel ran out of memory for allocating lock records.
EWOULDBLOCK: The file is locked and the LOCK_NB flag was selected.


How to display the number of images contained in a node using Views?

Question: I have a content type that has an image field (among other fields).
When creating a node, users can upload up to five files.
What i'm trying to do is to display how many images are uploaded in each node when listing node teasers using views ?
Thanks
Answer: Install the module: Field Count Formatter

A very simple module to provide a formatter for all field types. The
  output is simply a count of the number of items in that field. This is
  most useful on fields which have multiple values as it will show how
  many values are in this field.

Then in the teaser display for your content type, add the image field and set the formatter to count.
Comment: Ok, thanks i didn't know that module. Do you know if there's a way to achieve this without an additional module ?


O fundo do site não está sendo redimensionado junto com o @MEDIA

Question: Estou começando a utilizar o @media no CSS3, estou começando a produzir agora, mas quando eu coloco a visualização no chrome para qualquer dispositivo menor do que a resolução fica um fundo branco de 1200px e o objeto certo porém se o usuário puxar pro lado vai ficar tudo branco, me ajudem ai !

    <form>
  Usuário:                           Senha:

  <input type="text" name="usuario" placeholder="Digite seu usuário" required="required" class="usuario" autofocus="autofocus"/>

  <input type="password" name="senha" placeholder="Digite sua senha" required="required" class="senha"/>
  <input type="submit" value="Entrar" class="entrar">
  </form>
  Esqueceu a senha?

Cadastrar-se

  <input type="submit" value="Cadastre-se" class="cadastrese">

 Músicas mais curtidas

Comment: Poderia colocar uma imagem do que está acontecendo?
Answer: Issac vc colocou dois elementos (as duas últimas div com classe layout), elas têm a largura fixa em pixels, por isso está causando o scroll horizontal, troque a medida em PX por % que vai resolver o problema, isso não tem nada a ver diretamente com o @media...
Mas como vc colocou @media only screen and (max-device-width: 480px) vc só vai ver o @media funcionando se o sei device tiver tela menor que 480px, para simular isso no browser vc vai ter que usar o DelTools em modo responsivo (imagem 2)

Sobre o @media
Comment: Obrigado me salvou!


What should I do about composing 'soft' accents for piano?

Question: When composing for the piano, I often find myself writing a lot of sudden soft notes. I need an accent mark that suddenly softens notes. From my knowledge (and searching the web), I can not find any accent markings to soften a note. I have found many accent notes that emphasises a note and makes them louder (marcato) - but none that makes them softer.
I'm really suprised that I haven't found any accent markings for sudden soft notes. What can I do to write something like that? I really don't want to write 'subito P' over every note I want to soften. (Playing notes suddenly soft is one of my favorite things to write, so I use it a lot in my compositions.)
Comment: Have you considered "fp?"
Comment: @SRiss are you sure `fp` is ever used on non-tremoloed piano notes?
Comment: @NReilingh, you're correct.  I thought he was speaking from a purely notational stance and writing for a line or was using a keyboard and wanted to start a single note loudly and make it suddenly softer.  I now see that he is looking to create an inverted accent of sorts for a single note in passage (not "a lot of" suddenly soft notes)  Thank you for drawing my attention back to the question.  Maybe a light edit is in order?
Comment: I have seen "sp" used in piano music before, although I can't remember where. I think it would be obvious without having to write out "subito," especially since "sf" is very common, especially in Beethoven's music.
Answer: According to wikipedia, there are anti-accent marks commonly used by percussionists:
From slightly softer to really soft:

A 'u' (breve) above the note
() round parentheses around the note
[] square brackets around the note
Answer: Interesting question!
I'd say the "right" way to do this would probably be to just use dynamics (subito is probably not necessary). However, you may want to think about using alternate noteheads if you're composing something that is that dynamically active. There's no accepted doctrine to my knowledge, so you'd just provide a key that explains that an x notehead, for example, is played sub. pp.
Edit:
This came to mind after reading What is a ghost note ?
The x notehead as used in jazz is a sort of "anti-accent" that would probably be interpreted by a pianist as a softer note than the ones around it. I didn't think of jazz notation before, but I think it reinforces my argument above.
Answer: If you want a loud attack followed by a sudden decrease in sound, fp can be used on a single piano note.  Beethoven did it in the first movement of the Pathetique - it's a special technique in which one strikes the note and backs off of it slightly.  It might have worked better for 19th century pianos, but it has been notated this way.
However, if you simply want to alert the performer to the fact that this note should be subito piano, the best thing to do would be to write a performance note at the beginning of the piece, indicating that dynamic markings should be arrived at suddenly.  Look at a score by any of the total serialists, which usually have one dynamic marking per note.  In this performance style, every dynamic marking must be strictly followed to achieve the desired effect.  All you need to do is provide a note describing how dynamics are to be interpreted; no fancy symbols are necessary.
Comment: "one strikes the note and backs off of it slightly".   Explain, please?  With particular reference to the mechanism of a piano action where, once the hammer has been 'thrown' with a certain velocity the player has no further control.  And how this would have been different on a C19 piano.
Answer: Forzando fz and subito piano sp seem to be the two markings for what you describe, at least by definition. An isolated - "sudden" - loud or soft dynamic.
But, I also seem to remember, from long ago, a teacher telling me to just use basic dynamic marks. So, something like setting mf at the beginning, then for the soft accents put p, then immediately after write mf to reset the dynamic level. Like this example from Mozart, K 279, the andante movement...

...and according to the autograph score at IMSLP, those markings are from Mozart, not editorial additions.
You just want to do the opposite of the example. Instead of a baseline p with f accents and then a return to p, you want a baseline of f (or whatever you like) then soft p accents with a return back to baseline f.
Answer: It's funny how seldom this kind of accent is ever written, though such notes can be a really nice tool of expression. Often, they are just implied by the musical context and really necessary (like "dropping down" notes in the accompainment after a melodic theme has ended), something that I used to forget very often, thereby driving my guitar teacher mad. What she would do then was just striking out the notes I had played too loud (the note heads, not the stems like in acciaccatura). I always thought that this was standard notation for single soft notes, but coming to think of it's not really used in printed scores. Makes the point satisfyingly clear though, in my opinion.
Answer: Umm...
What about > over a note?
A sudden decrescendo?
EDIT: It's <>!!!
Sources: Musescore3
Comment: That's what a regular (loud) accent looks like.


Entity Registration module: Enable registration by default or programmatically

Question: By default, the Entity Registration module disables the registration. We need to enable it everytime a node is created from 'Manage Registrations - Settings' tab. How to automate the process?
I tried changing the 'status' value to '1' in registration_field_info() of registration.field.inc but it didn't work.
Is there a way to do it programmatically, otherwise?
Answer: <code>/**
* Implements hook_entity_insert().
*/
function registration_entity_insert($entity, $entity_type) {
  $registration_type = registration_get_entity_registration_type($entity_type, $entity);
  if ($registration_type !== FALSE) {
list($entity_id) = entity_extract_ids($entity_type, $entity);

$settings2 = array(
  'multiple_registrations' => 0,
  'from address' => variable_get('site_mail', ini_get('sendmail_from')),
);

$settings = array(
  'status' => 1,
  'capacity' => 0,
  'send_reminder' => 0,
  'settings' => serialize($settings2),
);

registration_update_entity_settings($entity_type, $entity_id, $settings);
//registration_entity_set_default_settings($entity_type, $entity);
 }
}
</code>
References:
http://drupal.org/node/1430870
http://drupal.org/node/1357280


Expectation of latent variables in Factor analysis Model

Question: I am going to through the theory behind factor analysis models given here
Let's say our model is \begin{align} y_i = \mathcal \Lambda x_i +\epsilon, \end{align}
where $y_i$ is the $p$-dimensional observation and $x_i \in \mathcal N (0,I_q) $  is the q-dimensional underlying latent variable.  $\Lambda $ is the loading matrix. $\epsilon \in \mathcal N(0,\Psi)$ is the error term.
Now I want to get the conditional expectation of latent variable $x$ given {$y,\Lambda,\Psi$}, i.e.
\begin{align} p(x|y,\Lambda,\Psi) \end{align}
Here is my attempt:
\begin{align} \Lambda x & = y - \epsilon \\
\implies \Lambda^{'}\Lambda x & = \Lambda^{'}(y - \epsilon) \\
\implies  x & = (\Lambda^{'}\Lambda)^{-1}(\Lambda^{'}(y - \epsilon)) \\\end{align}
If I take the conditional expected value of $x$ now, I get
 \begin{align} E(x|y,\Lambda,\Psi)&= E((\Lambda^{'}\Lambda)^{-1}(\Lambda^{'}(y - \epsilon))) \\
E(x|y,\Lambda,\Psi)&= ((\Lambda^{'}\Lambda)^{-1}(\Lambda^{'}(y - E(\epsilon)))) \\
E(x|y,\Lambda,\Psi)&= (\Lambda^{'}\Lambda)^{-1}(\Lambda^{'}y) \\\end{align}
But, the expression given on Slide 18 in the above slides, the conditional expected value of $x$ reads something likes $Λ (ΛΛ^T+ Ψ)^
{−1}y$
Can you please point out the mistake I am doing in my derivation. Thanks in advance!
Comment: I just updated to explain what went wrong with your proof. Basically, your method is also a perfectly fine way to do it, but you made the mistake of saying $E(\varepsilon | y_i ) = 0$ when that's not actually the case
Comment: That's brilliant! I think this answers my doubt completely!!
Comment: this was a sneaky error, I also set $E(\varepsilon | y) = 0$ the first time i went through it without even thinking about it :)
Answer: $\newcommand{\e}{\varepsilon}$$\newcommand{\L}{\Lambda}$We have $y_i = \mu + \L x_i + \e_i$.
We want to think of the jointly Gaussian RV
$$
{x_i \choose y_i} \sim \mathcal N\left({0 \choose \mu}, \begin{bmatrix} I & \L^T \\ \L & \L\L^T + \Psi\end{bmatrix} \right)
$$
(slide 17 in that pdf) and from this we get
$$
x_i | y_i \sim \mathcal N\left(\L^T(\L\L^T+\Psi)^{-1}(y_i - \mu), I - \L^T(\L\L^T+\Psi)^{-1}\L\right)
$$
(slide 18) so
$$
E(x_i \vert y_i, \L, \Psi) = \L^T(\L\L^T+\Psi)^{-1}(y_i - \mu).
$$

Here's where you went wrong:
$$
E(x_i | y_i) = (\L^T\L)^{-1}\L^T(y_i - \mu - E(\e | y_i))
$$
but the mistake is that while $E(\e) = 0$, $E(\e | y_i)$ is not necessarily $0$.
Again think of the joint distribution of ${\e \choose y_i}$. Note $Cov(\e, y_i) = Cov(\e, \L x_i + \e) = \Psi$ so
$$
{\e \choose y_i} \sim \mathcal N\left({0 \choose \mu}, \begin{bmatrix} \Psi & \Psi \\ \Psi & \L\L^T + \Psi\end{bmatrix}\right).
$$
This means
$$
E(\e|y_i) = \Psi(\L\L^T + \Psi)^{-1}(y - \mu)
$$
so taking $\mu = 0$ now for simplicity we have
$$
E(x_i | y_i) = (\L^T\L)^{-1}\L^T(y_i - \Psi(\L\L^T + \Psi)^{-1}y_i) \\
= (\L^T\L)^{-1}\L^T(I - \Psi(\L\L^T + \Psi)^{-1}) y_i.
$$
Now consider
$$
\L^T(\L\L^T+\Psi)^{-1} - (\L^T\L)^{-1}\L^T(I - \Psi(\L\L^T + \Psi)^{-1}) \\
= \L^T(\L\L^T+\Psi)^{-1} - (\L^T\L)^{-1}\L^T +  (\L^T\L)^{-1}\L^T \Psi(\L\L^T + \Psi)^{-1} \\
= \left(\L^T - (\L^T\L)^{-1}\L^T(\L\L^T + \Psi) + (\L^T\L)^{-1}\L^T \Psi\right)(\L\L^T + \Psi)^{-1} \\
= \left(\L^T - (\L^T\L)^{-1}\L^T\L\L^T - (\L^T\L)^{-1}\L^T \Psi + (\L^T\L)^{-1}\L^T \Psi\right)(\L\L^T + \Psi)^{-1} \\
= \left(\L^T - \L^T - (\L^T\L)^{-1}\L^T \Psi + (\L^T\L)^{-1}\L^T \Psi\right)(\L\L^T + \Psi)^{-1} \\
= \mathbf 0.
$$
This means
$$
\L^T(\L\L^T+\Psi)^{-1} = (\L^T\L)^{-1}\L^T(I - \Psi(\L\L^T + \Psi)^{-1})
$$
so actually this method, when correcting the mistake about $E(\e | y_i)$, yields the exact same answer! It just takes some work to turn one into the other.
Comment: I understand that my approach is flawed. Can you please also explain how the conditional distribution follows from the joint distribution in slide 17?
Comment: @kasa that part has been discussed on this site here: https://stats.stackexchange.com/questions/30588/deriving-the-conditional-distributions-of-a-multivariate-normal-distribution plus the wikipedia article for the multivariate normal discusses it a bit: https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Conditional_distributions


Using Drools rules to fill a DTO

Question: I am using Jasper Reports to prepare a PDF file containing data coming from a business application. On the server I prepare a DTO with lots of values depending on business decisions and feed it to a template prepared with iReport. Because with the time these business decisions are increasing in number and complexity, I'm trying to see how to formalize them as rules and entrust them to Drools.
I am fairly new to Drools; I've ran a few example from literature and web sources; presently I see the possibility of feeding the empty DTO to the Drools session along with the business objects and let the rule fill it, like in this minimal example:
DTO dto = new DTO();
session.insert(new Purchase(new BigDecimal("30")));
session.insert(dto);
session.fireAllRules()

A rule would look like this:
rule "purchase over 25 dollars"
when
    $p : Purchase ( total > 25 )
    $d : DTO ()
then
    $d.setDiscount(0.15);
end

I must admit all this looks a bit awkward to me. I wonder if there is a cleaner way to prepare the DTO using Drools.
Every Drools-based solution is welcome. NB: Moving the business logic in the iReport template is out of discussion.
Answer: What causes your feeling that this isn't "clean" enough? Each new programming paradigm looks somewhat strange to the novice, so drink another cup of strong espresso and get over it.
The Java code and the rule are basically OK as shown. Purchase is bound to be more complex, and so will be your DTO.
You could avoid the new and insert of the DTO in your Java code and do it using a rule; in this case (and for other reasons) the DTO should be linked to some specific Purchase:
rule "create DTO"
when
  $p: Purchase()
  not DTO( purchase == $p )
then
  insert new DTO( $p ) );
end

Linking a DTO to its Purchase is also a good strategy whenver there may be more than one DTO in the Working Memory at the same time. Speaking of which: you should also consider clean-up, i.e., getting the facts out of memory.
Comment: There's more than one way. (1) If you insert from Java, keep the reference of the object. (2) Use a global Collection (List) and add the DTO to it; after firing for all Purchase objects, all DTO's will be there. (3) You can investigate all DTOs using a "session" method. (4) As you wrote: link from the Purchase object. (5) I usually forget one option ;-) - Ah yes: a query (but this is overengineering).
Comment: I pursue immutability whenever I can and I found it awkward to insert an object in the session just to have it modified. I can live with it, though. One more question: how do I retrieve the `DTO($p)` from my Java code? I reckon the DTO constructor will have to put a reference inside the Purchase, am I right?

Using Drools rules to fill a DTO


Is $\frac{\partial}{\partial x_1}=\frac{\partial}{\partial y_1}$ if $x_1=y_1$?

Question: Let $M$ be a manifold, $p\in M$ and $(U,\varphi=(x_1,\dots,x_n))$, $(V,\psi=(y_1,\dots,y_n))$ two local charts such that $p\in U\cap V$ and $x_1=y_1$. Is it true that $(\frac{\partial}{\partial x_1})_p=(\frac{\partial}{\partial y_1})_p$?
My professor says that the answer is yes, and so I build a proof. But then I found the following counterexample:
Let $M=\mathbb{R}^2$, $p=(0,0)$, $U=V=\mathbb{R}^2$, $\varphi(u,v)=(u,v)$ and $\psi(u,v)=(u,u+v)$. Then $x_1(y_1,y_2)=y_1$ and $x_2(y_1,y_2)=y_2-y_1$. Using the formula for the change of basis I've got
$$(\frac{\partial}{\partial y_1})_p=\sum_{i=1}^2(\frac{\partial x_i}{\partial y_1})_p(\frac{\partial}{\partial x_i})_p=(\frac{\partial}{\partial x_2})_p-(\frac{\partial}{\partial x_1})_p\neq (\frac{\partial}{\partial x_1})_p$$
What's wrong with this counterexample?
Answer: Think the answer is no. There
Is nothing wrong with your example. There are plenty of examples where this could happen, in fact this is $\textbf{warned}$ in standard text in differential geometry e.g $\textbf{Lee's Smooth Manifold}$ page 65, by consider the coordinates $(x,y)$ and $(\tilde{x},\tilde{y})$ in $\mathbb{R}^2$ related by
$$
\tilde{x} = x, \qquad \tilde{y} = y+x^3
$$
Evaluate at $p=(x,y)=(1,0) \in \mathbb{R}^2$ will gives
$$
\frac{\partial}{\partial x}\Big|_p \neq \frac{\partial}{\partial \tilde{x}}\Big|_p.
$$
Which is tell us that $\frac{\partial}{\partial x^i}\Big|_p$ depend on the entire coordinate system, not just $x^i$.
Comment: Thank you, I'll talk to my professor, I probably misunderstood him :)
Answer: You have re-discovered a confusion with the Leibniz notation $$\frac{\partial u}{\partial x}$$ which has caught students for years.  The answer depends not only on the variable $x$, but also on what the other variables are.  So if you change the other variables, the value of $\frac{\partial u}{\partial x}$ could change, even if $x$ stays the same.
Hopefully, mathematicians are aware of this and avoid the problem.  But students, as well as users of math (such as physicists and engineers) do sometimes make such glaring errors.
Added:  The standard changes of coordinates are fixed so that this problem does not come up.  For example, the change between cartesian coordinates $(x,y,z)$ and cylindrical coordinates $(r,\theta, z)$.  Here, the coordinates $(r,\theta,z)$ are orthogonal in the $(x,y,z)$ coordinate system (and vice versa), so
$$
\frac{\partial u}{\partial z}
$$
is the same for both coordinate systems.  Challenge: Try proving this, as an exercise to see that you understand.
Comment: The truth is that I don't understand what is going on. I've even used the definition I've got to compute $\frac{\partial x_i}{\partial y_1}$, which is $\left.\frac{d (x_i\circ\alpha(t))}{dt}\right|_{t=0}$, where $\alpha=(t,0)$.
Comment: I put an example at https://math.stackexchange.com/a/3950472/442
Answer: The both variables can be reduced to the same function germ on the intersection of the chart, so the Members of the dual-space in the tangentialmanifold do coincide. The terminology function germ according to p in M , means to functions are in the same function germ equivalence class if they do coincide in an Environment of this point. So [x1]=[y1] as function germs and according to the definition the duals in Tangenspace do coincide. There is no need of a chart transformation anymore due to the fact that the functions are in the different Environment equivalent in the intersection of two open sets U and V.


I am new to Python and I wonder what is wrong with this code

Question: I am new to Python and I wonder what is wrong with this code, I searched for this,I guess in the end of the make_list function I have to return, and not print(). and in the end I have to write
if name[0]  and not if name[1], but what else is wrong with it?
Code:
def make_list(number):
    names = []
    for item in number:
        names.append(input("Enter your name with a capital letter."))
        print(names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [1] == 'A':
        print("Name", name, "starts with A")

Compiler says:
Traceback (most recent call last):
File "<string>", line 8, in <module>
File "<string>", line 3, in make_list
TypeError: 'int' object is not iterable

Comment: Python doesn't know what e.g. `for item in 3` is supposed to mean. In for loop, you need some kind of iterable, so e.g. [0, 1, 2], which you can get by using `range(3)`
Comment: Should be `for item in range(number):`
Comment: `number` is an int, so `for item in number` does not make sense. Also `make_list` doesn't return anything.
Comment: Potential Duplicate: https://stackoverflow.com/questions/14941288/how-do-i-fix-typeerror-int-object-is-not-iterable
Comment: Does this answer your question? [How do I fix TypeError: 'int' object is not iterable?](https://stackoverflow.com/questions/14941288/how-do-i-fix-typeerror-int-object-is-not-iterable)
Answer: You need to have range(numbers) to iterate, and you also forgot to return names from the make_list function. Also, as the arrays in Python are zero-indexed, you probably want to check if name [0]
def make_list(number):
    names = []
    for item in range(number):
        names.append(input("Enter your name with a capital letter."))
        print(names)
    return names

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
    if name [0] == 'A':
        print("Name", name, "starts with A")

Answer: This is my solution:
def make_list(number):
    names = []
    for _ in range(number):
        names.append(input("Enter your name with a capital letter: "))
        print(names)
    return(names)

number = int(input("How many names need to be entered? "))
names = make_list(number)
for name in names:
    if name.startswith('A'):
        print("Name", name, "starts with A")

Results:
How many names need to be entered?3
Enter your name with a capital letter.RUNE
['RUNE']
Enter your name with a capital letter.PETER
['RUNE', 'PETER']
Enter your name with a capital letter.ANDERS
['RUNE', 'PETER', 'ANDERS']
Name ANDERS starts with A

Comment: This also works, good answer, however I would suggest changing the return statement from the function from: `return(names)` to just `return names`
Comment: _Generally the convention would be to not use brackets on a return statement_
Answer: In python you can not loop through an integer. Try to switch for item in number with for item in range(number) I think this will solve your problem.
Comment: This is not the only problem, the other issue that @user23952 also addressed is that the `make_list` function is not returning `names` as well as the correction from `if name[1] =='A'` to `if name[0]=='A'`. I don't know why this has an upvote when it clearly only fixes one part of the problem and the correct answer has already been posted by @user23952 here: https://stackoverflow.com/questions/71062965/i-am-new-to-python-and-i-wonder-what-is-wrong-with-this-code/71063027#71063027
Comment: I suggest you edit your answer to include this or  maybe you can delete your answer as a more complete answer has already been posted
Answer: for item in number: looks like you are attemping to repeat the loop number times. In python you do that like this: for item in range(0, number):. item will range from 0 to number-1
Comment: Andy Brown, Thanks!
Comment: While this does solve one part of the answer, a more complete answer has been posted here: https://stackoverflow.com/questions/71062965/i-am-new-to-python-and-i-wonder-what-is-wrong-with-this-code/71063027#71063027. I suggest you edit your answer to include this or delete it as a more complete answer has already been posted
Answer: actually number is an integer, the error is saying in line 3 you are trying to loop through an integer which is not possible
Wrong : for item in number
What you may do instead : for item in range(number)
Here is some reading on the range function https://www.w3schools.com/python/ref_func_range.asp
Comment: While this does get rid of the error, it doesn't solve the 2 other problems with the return from the function and the `name[1]` to `name[0]`, I suggest you either edit your answer to include this, or just delete your answer as a more complete answer has already been posted here https://stackoverflow.com/questions/71062965/i-am-new-to-python-and-i-wonder-what-is-wrong-with-this-code/71063027#71063027


Open Multidatepicker on button click

Question: When I try to hide an input containing the dates selected by the user with :
style = "display:none"

The picker does display anymore.
I absolutely need to hide this input since the only thing the user must see is the button he clicks to open the picker.
HTML:
<input type="button" value="Répercuter" class="button" id="btnRepercute"/>
<input type="text" name="dateMultiCalendar_1" id="dateMultiCalendar_1" class="dateMultiCalendar_1"/>

JS:
$('#dateMultiCalendar_1').multiDatesPicker($.datepicker.regional[ "fr" ]);
$('#btnRepercute').click(function() {
$("#dateMultiCalendar_1").datepicker( "destroy" );
$('#dateMultiCalendar_1').multiDatesPicker
({

           // $.datepicker.regional[ "fr" ]
           //beforeShowDay: $.datepicker.noWeekends
        beforeShowDay: function (date) {
         var today = new Date();
           if (date.getDay() === 1 || date.getDay() === 2 || date.getDay() === 3
           || date.getDay() === 4 || date.getDay() === 5)

           {
            if (date.getMonth() === today.getMonth())
                {
                    return [true, ''];
                }
           }
        return [false, ''];
        }

});
 $('#dateMultiCalendar_1').focus();
});

I just noticed that when I click on the button to display the picker, the calendar always displays under the input and never under the button. Maybe the reason why when I hide the input, the calendar no longer appears.
Answer: Your code does not work because you cannot give focus to a non-displayed field.
However you can display the date picker from javascript using datepicker('show').
(Not that in this instance we use datepicker and not multiDatesPicker)
Try this :
//Attach the date picker to you text field
$('#dateMultiCalendar_1').multiDatesPicker({
           beforeShowDay: function (date) {
                var today = new Date();
                if (date.getDay() >= 1 && date.getDay() <= 5){
                   if (date.getMonth() === today.getMonth(){
                      return [true, ''];
                   }
                }
                return [false, ''];
           }
 });

//Make the button display the date picker on cick
$('#btnRepercute').click(function() {
         $('#dateMultiCalendar_1').datepicker('show');
});

Comment: Thx a lot for sharing yout knowledge
Answer: [updated]
$('#dateMultiCalendar_1').hide();
$('#dateMultiCalendar_1').datepicker({
           // $.datepicker.regional[ "fr" ]
           //beforeShowDay: $.datepicker.noWeekends
    beforeShowDay: function (date) {
    var today = new Date();
    if (date.getDay() >= 1 && date.getDay() <= 5)
    {
       if (date.getMonth() === today.getMonth())
          {
              return [true, ''];
          }
       }
       return [false, ''];
     },
  showOn: "button"
});
$('.ui-datepicker-trigger').text('whatever');

Sorry I couldn't get back to you in time, but it seems that you got your answer already, here would be mine anyways:
$('#dateMultiCalendar_1').hide();
$('#dateMultiCalendar_1').multiDatesPicker({
    beforeShowDay: function (date) {
        if (date.getDay() >= 1 && date.getDay() <= 5)
            return [true, ''];
        else
            return [false, ''];
     }
});

$('#btnRepercute').click(function(){
    $('#dateMultiCalendar_1').toggle('show');
});

and here is the fiddle : click me
Comment: Thanks for your help but the multidatepicker always closes when i select a date!

Open Multidatepicker on button click


Can't connect Websphere MQ Queue Manager

Question: I'm a beginner on WebSphere MQ, I was working on MQ 6 and it was working fine, but now I've installed MQ 7.1 and when I try to create a new Queue Manager I can do it But it can't connect and it gives me the following error :

Do you have any idea about that? Thank you :)
Answer: You can look up any WebSphere MQ error code if either the WebSphere MQ Client or Server are installed using the mqrc command.  In this case:
C:\Users\MUSR_MQADMIN>mqrc 2059

      2059  0x0000080b  MQRC_Q_MGR_NOT_AVAILABLE

The 2059 usually indicates that the listener is not running or the queue manager is down.  There's a different error code if the listener is running and the QMgr name is wrong and another one if the connection is made to the right QMgr but the channel name is wrong.  Sometimes you can get a 2059 if the channel was closed at the server side by an exit but since you didn't mention any exits, I'm assuming in this case that its  listener problem.
Hopefully by now you are defining a listener object rather than using inetd or the runmqlsr command.  Defining an object and setting it to start and stop under QMgr control is the most reliable way to configure it.
Once you get past the 2059, you should be aware that as of WMQ V7.1, the queue managers are secure by default and won't accept any remote client connections unless you explicitly authorize them.  This is the opposite of the behavior of V6 where on a newly defined queue manager running a listener, anyone with a TCP route to it could administer it and remotely execute OS code as the mqm user.  So I expect that the next problem you run into will be 2035 errors.
I've been told this means more work for the WMQ administrator.  The only case in which that's true is if the V6 or earlier queue manager had been configured without security.  If the tasks to secure a V7.0 QMgr are compared to the tasks to provision access on a v7.1 and higher QMgr are compared, provisioning access turnds out to be easier.  However if you liked the V7.0 behavior, you can always alter the QMgr to disable CHLAUTH rules.  Needless to say, leaving security enabled is highly encouraged.
To debug security errors, alter the QMgr to enable authorization events using the runmqsc command ALTER QMGR AUTHOREV(ENABLED).  Next, download and install SupportPac MS0P into WebSphere MQ Explorer.  Then when you do get a security error, use WebSphere MQ Explorer to look at the queue.  Right-click on the queue and select the option to parse the event messages.  This will tell you in excruciating detail all the information you need to debug the authorization error.
Finally, if you wish to read up on the new security features, go to t-rob.net/links and look at the conference presentations there.  There are also some articles indexed if you scroll down.
Comment: Thank you. I didn't install MQ client or MQ Server, I've only installed the WebSphere MQ Distribution platform here : http://ibm.co/X7SXF6 . Should I install the client and the server to use the `mqrc` command ?
Comment: The WMQ Explorer (SupportPac MS0T that you linked to) has its own built-in client and isn't meant to be the redistributable client.  It doesn't have all the features that the full WMQ Java client does.  For what it's worth, I've asked the lab to include mqrc in the Explorer install.  In any case, glad you got it working.
Answer: In the screen-shot, I see hostname "127.0.0.1" and port # 1414.  If it is a local queue manager then connect directly to it.
Also, each queue manager MUST use a unique port number. If you had it working with WMQ v6 queue manager, is this the same queue manager?  If not, then make sure each queue manager uses a different port number (i.e. 1415, 1416, etc...)
Answer: I got same problem. but i resolved this by :
1. created a listener manually (define lstr(lstr1) port(xxxx) control(qmgr)
2. setmqaut mcauser('mqm').


Erro Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

Question: Estou com esse erro e não consigo resolvê-lo, dá toda vez que executo o app.
LogCat:
01-15 16:09:03.380    2473-2473/com.prjctt.allan.financeiro
E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.prjctt.allan.financeiro, PID: 2473
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.prjctt.allan.financeiro/com.prjctt.allan.financeiro.ListDespesasActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
android.view.View android.view.Window.findViewById(int) on a null
object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method android.view.View
android.view.Window.findViewById(int) on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.prjctt.allan.financeiro.ListDespesasActivity.<init>(ListDespesasActivity.java:20)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Classe aonde ocorre o erro:
public class ListDespesasActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    DespesaDAO despesa = new DespesaDAO(this);
    List<Despesa> list = despesa.getLista();
    setListAdapter(new DespesaAdapter(this,list));

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_list_despesas, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case R.id.action_add_despesa:
            Intent intent = new Intent(this, EditaDespesaActivity.class);
            startActivity(intent);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

Classe DespesaDAO:
public class DespesaDAO extends SQLiteOpenHelper {
private static final String NOME_BD = "mobfin";
private static final String TABELA = "Despesa";
private static final String[] COLUNAS = {"_id", "valor", "data", "descricao", "pago", "idgrupo", "idsubgrupo", "idusuario", "incluidoem", "sincronizado"};
private static final int VERSION = 1;

public DespesaDAO(Context context) {
    super(context, TABELA, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE " + TABELA + "( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
            " valor DOUBLE NOT NULL," +
            "data DATETIME NOT NULL," +
            " descricao TEXT NOT NULL," +
            " pago SMALLINT NOT NULL," +
            " idgrupo INT," +
            " idsubgrupo INT," +
            " idusuario INT," +
            " incluidoem DATETIME NOT NULL," +
            " sincronizado SMALLINT NOT NULL);";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DespesaDAO.TABELA);
    this.onCreate(db);
}

public void inserir(Despesa despesa) {
    ContentValues valores = new ContentValues();
    valores.put("valor", despesa.getValor());
    valores.put("data", despesa.getData().toString());
    valores.put("descricao", despesa.getDescricao());
    valores.put("pago", despesa.isPago());
    valores.put("idgrupo", despesa.getIdGrupo());
    valores.put("idsubgrupo", despesa.getIdSubgrupo());
    valores.put("incluidoem", despesa.getIncluidoEm().toString());
    valores.put("sincronizado", despesa.isSincronizado());

    getWritableDatabase().insert(TABELA, null, valores);
}

public void atualizar(Despesa despesa) {
    ContentValues valores = new ContentValues();
    valores.put("valor", despesa.getValor());
    valores.put("data", despesa.getData());
    valores.put("descricao", despesa.getDescricao());
    valores.put("pago", despesa.isPago());
    valores.put("idgrupo", despesa.getIdGrupo());
    valores.put("idsubgrupo", despesa.getIdSubgrupo());
    valores.put("idusuario", despesa.getIdUsuario());
    valores.put("sincronizado", despesa.isSincronizado());

    this.getWritableDatabase().update("despesa", valores, "_id = ?", new String[]{"" + despesa.getId()});
}

public void deletar (Despesa despesa){
    this.getWritableDatabase().delete("despesa", "_id = " + despesa.getId(), null);
}

public List<Despesa> getLista() {
    Cursor c = getWritableDatabase().query(TABELA, COLUNAS, null, null, null, null, null);
    List<Despesa> lista = new ArrayList<>();

    while (c.moveToNext()) {
        Despesa despesa = new Despesa();
        despesa.setId(c.getInt(0));
        despesa.setValor(c.getString(1));
        //despesa.setData(2);
        despesa.setDescricao(c.getString(3));
        despesa.setPago(c.getString(4).equalsIgnoreCase("TRUE"));
        despesa.setIdGrupo(c.getInt(5));
        despesa.setIdSubgrupo(c.getInt(6));
     //   despesa.setIncluidoEm(c.getString(7));
        despesa.setSincronizado(c.getString(8).equalsIgnoreCase("TRUE"));

        lista.add(despesa);
    }
    c.close();

    return lista;
}

}

Adapter
public class DespesaAdapter extends BaseAdapter {
private Context context;
private List<Despesa> lista;
ListView listView;

public DespesaAdapter(Context context, List<Despesa> lista) {
    this.context = context;
    this.lista = lista;
}

@Override
public int getCount() {
    return lista.size();
}

@Override
public Object getItem(int position) {
    return lista.get(position);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    final int auxPosition = position;

    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final LinearLayout layout = (LinearLayout)
            inflater.inflate(R.layout.despesas, null);

    TextView tvNome = (TextView)
            layout.findViewById(R.id.tvDesp);
    tvNome.setText(lista.get(position).getDescricao());

    TextView tvValor = (TextView)
            layout.findViewById(R.id.tvVal);
    tvValor.setText(lista.get(position).getValor());

    ImageButton btEditar = (ImageButton)
            layout.findViewById(R.id.btEdit);
    btEditar.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, EditaDespesaActivity.class);
            intent.putExtra("valor", lista.get(auxPosition).getValor());
            intent.putExtra("data", lista.get(auxPosition).getData());
            intent.putExtra("descricao", lista.get(auxPosition).getDescricao());
            context.startActivity(intent);
        }
    });

    ImageButton btDelete = (ImageButton)
            layout.findViewById(R.id.btDelete);
    btDelete.setOnClickListener(new ImageButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            DespesaDAO despesa = new DespesaDAO(context);
            despesa.deletar(lista.get(auxPosition));

            layout.setVisibility(View.GONE);
        }
    });

    return layout;
}
}

Comment: Allan, você está chamando o método `findViewById` em um momento onde a `View` dessa `Activity` ainda não foi inflada e populada. Poderia indicar a classe `DespesaDAO`?
Comment: Editado com a classe DespesaDAO @Wakim
Comment: Poderia identificar a linha 20 do `ListDespesasActivity`? Achei que era o método `despesa.getLista`, mas não é. A princípio você precisa chamar o método `setContentView` após o `super.onCreate` e antes de qualquer coisa que manipule as `Views`.
Comment: a linha 20 seria essa @Wakim :
super.onCreate(savedInstanceState);

Eu estou usando uma classe adapter pra inflar um layout, o app estava rodando até agora pouco, eu inseri algumas linhas e começou a dar esse erro, quando essas linhas foram  tiradas o erro persistiu.
Comment: Estranho, ali ele cita que o construtor da sua `Activity`, mas na pergunta não vejo isso. Mas também não vejo como você seta o layout da `Activity`.
Comment: Na linha setListAdapter(new DespesaAdapter(this,list)); @Wakim. Vou inserir o adapter pra você dar uma olhada.
Comment: eu disse sobre o construtor da `Activity`, não do `Adapter` (`com.prjctt.allan.financeiro.ListDespesasActivity.`). Essa é a `Activity`, atualizada, que deu erro?
Comment: O erro parou de acontecer, agradeço todas as respostas, não sei oq houve, hoje liguei o notebook, fui testar e o erro não aconteceu.
Answer: O seu ListDespesasActivity tem que tratar o setListAdapter da forma correta. Ele deve ser chamado antes de qualquer coisa. Veja um exemplo:
public class MyListAdapter extends ListActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState){
         super.onCreate(savedInstanceState);

    // Vamos definir um layout de tela personalizada aqui, mas
         // Normalmente , você pode simplesmente usar o layout ListActivity padrão.
         setContentView(R.layout.custom_list_activity_view);

         // Query for all people contacts using the Contacts.People convenience class.
         // Put a managed wrapper around the retrieved cursor so we don't have to worry about
         // requerying or closing it as the activity changes state.
         mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
         startManagingCursor(mCursor);

         // Agora criar um novo adaptador vinculado ao cursor.
     // SimpleListAdapter é projetado para ligar a um Cursor.
         ListAdapter adapter = new SimpleCursorAdapter(
                 this, // Context.
                 android.R.layout.two_line_list_item,  // Specify the row template to use (here, two columns bound to the two retrieved cursor
 rows).
                 mCursor,                                              // Pass in the cursor to bind to.
                 new String[] {People.NAME, People.COMPANY},           // Array of cursor columns to bind to.
                 new int[] {android.R.id.text1, android.R.id.text2});  // Parallel array of which template objects to bind to those columns.

         // Bind to our new adapter.
         setListAdapter(adapter);
     }
 }

Veja mais sobre ListActivity em: http://developer.android.com/reference/android/app/ListActivity.html


What is the expected value of the mean of the highest $m$ numbers in a population of $N$ normally distributed random variables?

Question:
Suppose that I randomly generate $N$ numbers according to the standard normal distribution, $\mathcal{N}(0,1)$.  Then suppose I pick the highest $m$ numbers, $x_1\leq x_2 \leq \cdots \leq x_m$.  What is the expected value of the (arithmetic) average of $x_1,\dotsc , x_m$?

Forgive me, I couldn't get my probability theory phrasing 100% accurate here.  Hopefully my meaning is clear.

EDIT: A better attempt at proper phrasing might be,

If $a_1,\dotsc , a_N$ are real numbers and $m<N$, define $y_m(a_1,\dotsc , a_N)$ to be the average of the top $m$ values among $a_1,\ldots ,a_N$.  If $X_1,\dotsc ,X_N\sim \mathcal{N}(0,1)$ are i.i.d. r.v.'s, define $Y=y_m(X_1,\dotsc ,X_N)$.  What is $\mathbb{E}(Y)$?

(Would be greatful foro suggestions on how to improve the formal statement here.)
Comment: Note: this question has been asked before [here](http://math.stackexchange.com/q/388926/53776) for uniformly distributed variables, but the link in the answer is broken.  It was also asked [here](http://math.stackexchange.com/a/117996/53776), but the answer given was for uniformly distributed random variables.
Answer: You can derive the result from this answer on Cross Validated.
By linearity of expectation, you just need to add the top $m$ order statistics and divide by $m$.
Answer: To answer this question, one must note that by generating a random number from a distribution with cumulative distribution function $F$, one is uniformly sampling the y-axis and choosing the x-axis value. Hence, we should first find the corresponding $x$-value of the partition chosen, that is $$\frac{1}{{\sqrt {2\pi } }}\int\limits_x^{ + \infty } {{e^{ - \frac{{{t^2}}}{2}}}dt}  = \frac{M}{N}$$which yields $$x = \sqrt 2 {\rm{InverseErfc}}\left( {\frac{{2M}}{N}} \right)$$Now, all we have to compute is the expected value of $x$ in this range, that is $$\begin{array}{c}{\rm{Answer}} = \frac{{\frac{1}{{\sqrt {2\pi } }}\int\limits_{\sqrt 2 {\rm{InverseErfc}}\left( {\frac{{2M}}{N}} \right)}^{ + \infty } {t{e^{ - \frac{{{t^2}}}{2}}}dt} }}{{\frac{1}{{\sqrt {2\pi } }}\int\limits_{\sqrt 2 {\rm{InverseErfc}}\left( {\frac{{2M}}{N}} \right)}^{ + \infty } {{e^{ - \frac{{{t^2}}}{2}}}dt} }}\\ = \frac{N}{{\sqrt {2\pi } M}}{e^{ - \frac{{{{\left( {{\rm{InverseErfc}}\left( {\frac{{2M}}{N}} \right)} \right)}^2}}}{2}}}\end{array}$$A plot could be constructed for this problem by defining $u = \frac{N}{M}$ and noticing that $1 \le u <  + \infty $  Hope it helps ;)


Unit conversion kilometers to miles doesn't return the expected result

Question: I am trying to convert my result from kilometers to miles but the result I get isn't correct.
What seems to be the problem here?
when {
    // TIME: To calculate your time, fill in your distance and pace
    time == null -> {
        val calculatedTime = distance!!.toLong() * timeToSeconds(pace.toString())
        result.text = "The runner's time is ${secondsToTime(calculatedTime)}"
    }
    // DISTANCE: To calculate your distance, fill in your time and pace
    distance == null -> {
        val calculatedDistance = ((timeToSeconds(time).div(timeToSeconds
        (pace.toString()))) * 0.621371).format(2)
        result.text = "Distance is $calculatedDistance Miles"
    }
    // PACE: To calculate your pace, fill in your time and distance
    pace == null -> {
        // Calculate Pace
        val calculatedPace: Long = timeToSeconds(time).toLong() / distance.toLong()

        Log.i("PaceSeconds", calculatedPace.toString() +
                secondsToTime(calculatedPace))

        result.text = "The runner's pace in miles is ${secondsToTime(calculatedPace)}"
    }
}

Comment: Please post just one part of the code with its inputs and expected outputs. Also, if you don't know what's happening when your code is executed, use the debugger to follow the values in it.
Comment: "Android not applying math correclty" that's quite a statement :D I suggest you to write a small test case, to verify your calculations are correct
Comment: Please provide more details about what is not correct, what you expect from this code and what research you have already done. Questions asking for debugging help and only providing the sources without an explanation are considered off-topic on StackOverflow.
Comment: A simple calculation: for 10:12 (minutes and seconds) at a pace of 1:23 (mm:ss again) the distance in KM is 7.37 (and I get that value correctly). Although, when I convert it to Miles, it gives me 4.35 when it should give me 4.58 Miles
Comment: I did verify the calculations on a paper before writing them :)
Comment: I put a breakpoint on the val I calculate it and I see the value being passed as 4.35 instead of 4.58. So weird. I even tried using toDouble
Answer: This is a rounding issue. Lets break it down:
val timeInSeconds = timeToSeconds(time)
val paceInSeconds = timeToSeconds(pace)
val timeDivPace = timeInSeconds.div(paceInSeconds)
val calculatedDistance = timeDivPace * 0.621371

Using the sample data from your comment, timeInSeconds is 612 and paceInSeconds is 83. You expect timeDivPace to be 7.373494 but it actually is 7 because a division of two integers returns an integer as result.
The fix is simple: convert either the dividend or the divisor to float, e.g.:
val timeDivPace = timeInSeconds.div(paceInSeconds.toFloat())


If statement with Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

Question: I'm trying to make a GUI where you have to fill in some information to add a customer.
In cases when not all the information is provided, I'd like to have a popup that says you have to fill in all info, but I keep getting the same error.
If you enter all info, the code works and saves to an SQL database:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String firstname = txtfirstname.getText();
    String lastname = txtlastname.getText();
    String country = txtcountry.getText();
    int passport = Integer.parseInt(txtpassport.getText());

    DateFormat da = new SimpleDateFormat("dd/MM/yyyy");
    String date = da.format(txtdate.getDate());

    if(firstname.equals("")||txtlastname.getText().equals("")||txtcountry.getText().equals("")||txtpassport.getText().equals("")||da.format(txtdate.getDate()).equals("")){
     JOptionPane.showMessageDialog(null,"All fields have to be filled in....");

    }else{

    try {
  DBCustomer.save(new Customer(firstname, lastname, passport, date, country));
  JOptionPane.showMessageDialog(null,"Registration created");
  txtfirstname.setText("");
  txtlastname.setText("");
  txtcountry.setText("");
  txtpassport.setText("");
  txtdate.setDate(null);

} catch (DBException ex) {
  Logger.getLogger(DBCustomer.class.getName()).log(Level.SEVERE, null, ex);
}

  }

}

this is the exception i keep getting
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at project.gui.addCustomer.jButton1ActionPerformed(addCustomer.java:225)
at project.gui.addCustomer.access$000(addCustomer.java:31)
at project.gui.addCustomer$1.actionPerformed(addCustomer.java:173)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Comment: You cannot parse an empty string to a Number. That is why it generates an exception. Empty string is not Radix 10.
Comment: You have to catch your exception before it is thrown. I would put that block of code in a try catch
Comment: Could you please give me an upvote. I am pretty sure that your are not getting the exception anymore.
Answer: Based on Java Doc.
public static int parseInt(String s)
                    throws NumberFormatException

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.

Answer: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String firstname = txtfirstname.getText();
    String lastname = txtlastname.getText();
    String country = txtcountry.getText();
try{
    int passport = Integer.parseInt(txtpassport.getText());
}
catch(NumberFormatException e)
{
   //Here you could put your code to display a popup saying that
   // Passport number is required
}

    DateFormat da = new SimpleDateFormat("dd/MM/yyyy");
    String date = da.format(txtdate.getDate());

    if(firstname.equals("")||txtlastname.getText().equals("")||txtcountry.getText().equals("")||txtpassport.getText().equals("")||da.format(txtdate.getDate()).equals("")){
     JOptionPane.showMessageDialog(null,"All fields have to be filled in....");

    }else{

    try {
  DBCustomer.save(new Customer(firstname, lastname, passport, date, country));
  JOptionPane.showMessageDialog(null,"Registration created");
  txtfirstname.setText("");
  txtlastname.setText("");
  txtcountry.setText("");
  txtpassport.setText("");
  txtdate.setDate(null);

} catch (DBException ex) {
  Logger.getLogger(DBCustomer.class.getName()).log(Level.SEVERE, null, ex);
}

  }

}


Where is a good JavaScript reference for object event handlers?

Question: I am relatively new to JavaScript and constantly need to look up how to handle various events for objects.  For example, I have a table containing a few text fields and need to know when somebody starts typing in any of the text boxes.  Is there any good concise reference on the web anyplace that documents all of the objects and event handlers associated with all objects?  I'd like to be able to look up the object and see all of the events I can handle for that object.
Comment: Specifically, the concept of "event delegation" would be a great choice here.
Answer: Checkout mozillas javascript ducmentation on addEventListener https://developer.mozilla.org/en/DOM/element.addEventListener
and the w3 spec page, section about event flow: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
Answer: http://www.webreference.com/javascript/reference/core_ref/contents.html
http://www.javascript.com/
and later on
www.jquery.com
Answer: Take a look at the events section here:
http://www.quirksmode.org/js/contents.html
Answer: Event handler properties vary a little between browsers. Check Mozillas documentation, the w3c events specification linked, and MSDN.


Mac OS X GUI in Assembly

Question: Is it possible to make a Mac OS X GUI in assembly bypassing the need for Objective C like Windows and Linux allow?
Comment: Yes, you can write any program in assembly that you could write in Objective-C.  It might not be very fun, though. What's your real question?
Answer: Yes, of course.  You can write an entire application in nothing but assembly, if you want.
What you can't avoid is calls into the framework APIs to setup and run the application.
Thus, you'll be spending a bunch of time writing assembly that sets up call sites into objc_msgSend() and/or framework C functions.
Create a new project in Xcode and then go to any source file and "show assembly".   There is the assembly version and you could certainly use that as your starting point.
Answer: No, not really. Most of the major libraries which you need to write a GUI application for Mac OS X (e.g, Cocoa and AppKit) are written in Objective C, and must be called from code that's written in that language as well. While it's technically possible to replicate the same effects in assembly, at that point you're basically just writing ObjC in a really awkward way.
There is an older GUI library for Mac OS X (Carbon) that is usable from C (and thus could potentially be used from assembly as well), but it is only available in 32-bit mode, and is deprecated. Don't use it for new code.
Comment: You can write an app in pure assembly, you'll just be setting up the call frames and JMP'ing to objc_msgSend() frequently.
Comment: Yup -- which is no different than Windows/Linux (unless their security model is just flat out non-existent).
Comment: Of course. But, like I said, at that point you're really just writing ObjC in assembly.

Mac OS X GUI in Assembly


VBO custom action: get the list of selected items

Question: I need to create an vbo action to produce a document (pdf) with a page for every item selected in the list.
Using im using hook_action_info but the callback get called once for every item selected; I need to have a function that get called with the list of selected items.
I've seen the Pass ids as arguments to a page action, that can fit my needs, but hey I'll love to avoid having such kind of urls (if possible, of course)
Is possible?
Answer: You don't do it at once, you generate the document page by page (item by item).
The document gets created on first run, and on the last run you do whatever cleanup you need.
See archive.action.inc that ships with VBO for an example of this approach.
You can mark your action as "aggregate", and get all rows, but that's going to significantly limit the number of items you can add to the document (depending on your memory limit). VBO is designed to work item-by-item.
Comment: That's perfectly fine. The archive action does stuff on the last run as well.

This is how VBO is supposed to work. Item by item. Otherwise you run out of resources.
Comment: On every run, i can check if the html file exists or not and then append the data, but i need on the last run to invoke the pdf converter (wkhtmltopdf). Anyway, this looks to me as a trick, and not a solution..
Answer: First, I need to point out that what you are trying to do is not a smart use of VBO. VBO is usually used with single-off tasks like publishing a single node or sending an email.
In your worker function (key of your hook_action_info() return array), you can receive an extra argument that has meta information of the current running task and total number of tasks.
You can however do some ninja work to set another batch work and append the generate PDF function there but it's difficult to do in most cases.


Minimizing a function in $\mathbb R^3.$

Question: I am currently solving the following task:
Exercise. Minimize in $\mathbb R^3$ the function $f(x_1,x_2,x_3) = x_1^2 + x_2^2 + x_3^2 - x_1x_2 + x_2x_3 - x_1x_3.$
My attempt. I was able to show that $(0,0,0)$ is a local  strict minimizer (consequently, $f(0,0,0) = 0$ is a local strict minimum) using the usual arguments, i.e., I found the critical points of $f$ (which is only one, $(0,0,0)$); then, I found the hessian of $f$ in the point $(0,0,0)$ and proved it was positive defined. Therefore, from the theorem below I am able to guarantee that $(0,0,0)$ is a local strict minimizer.
Theorem. Assume that $f$ is twice differentiable in $\bar x \in X.$ Then, if $\nabla f(\bar x) = 0$ and $H(\bar x) = \nabla ^2 f(\bar x)$ is positive defined, then $\bar x$ is a local strict minimizer.
My question. After this, one question comes up to my mind: is $(0,0,0)$ a global minimizer? Looking to answer this further question, I gave some values to some of the coordinates ($x_1, x_2 $ or $x_3$) individually and plotted the resultant graphs (which are $3D$). Every one I plotted (and I plotted a nice quantity...) leads me to the same conclusion: $(0,0,0)$ is, in fact, a global minimizer. After this, I tried to prove analitically that $f(x_1,x_2,x_3) \geqslant 0,$ for every $(x_1,x_2,x_3) \in \mathbb R^3$ (to show that, in fact $(0,0,0)$ is a global minimizer). But I am having a real hard time doing this. Any help towards proving this is apreciatted in advance.
Answer: If $$f_1(x_1,y_1,z_1) = \frac{1}{2} \left[ (x_1-x_2)^2 + (x_2-x_3)^2+(x_3-x_1)^2\right],$$
There would be infinitely many solutions along the line
$$x_1=x_2=x_3.$$
But, alas, $ f(x_1, x_2, x_3) = f_1(x_1, x_2, x_3) +2x_2 x_3 =\frac{1}{2} \left[ (x_1-x_2)^2 + (x_2+x_3)^2+(x_3-x_1)^2\right].$
Now we have all non-negative terms, so the solution must be that all terms are zero.  Solving $x_1=x_2=-x_3=-x_1$, the global solution is $(0,0,0)$.
Had some help with this (see comments below).
Comment: Are you sure of the signs of the mixed terms?
Comment: $\frac12((x_1-x_2)^2+(x_2-x_3)^2+(x_3-x_1)^2)=x_1^2+x_2^2+x_3^2-x_1x_2-x_2x_3-x_1x_3\ne f(x_1,x_2,x_3)$.
Comment: You are both correct.  I looked at the question too quickly.  Will update ...
Comment: Yes maybe you have just to change x2-x3 with x2+x3
Comment: Yes, $f(x_1,y_1,z_1) = \frac{1}{2} \left[ (x_1-x_2)^2 + (x_2-x_3)^2+(x_3-x_1)^2\right] + 2x_2x_3$ and $f(x_1,y_1,z_1) = \frac{1}{2} \left[ (x_1-x_2)^2 + (x_2+x_3)^2+(x_3-x_1)^2\right].$
Comment: Looks like $(0,0,0)$ is a local minimum after all.
Comment: As the OP observed :). It would be nice to see if the OP is satisfied with a sum of squares approach...
Comment: Your choice. Maybe you can make a new answer with the correct decomposition?
Comment: Maybe I am not sure what you mean. It helps because you showed that the minimum is when the three therms are all zero and this happens only when x1=x2=x3=0. Therefore this is a global minimum. But this is proven than without analysis and maybe the OP wanted an analysis driven solution?
Comment: Okay, you are right.  This is a solution!
Comment: Hello everyone! Thanks for your help. I am fine with a not so much analysis driven solution - this is just fine!
Answer: Notice that, for each $u,v\in\mathbb{R}$, it is $uv\le \frac{1}{2}u^2+\frac{1}{2}v^2$, because $0\le(u-v)^2=u^2-2uv+v^2$. Hence, for each $u,v\in\mathbb{R}$ it is $-uv \ge -\frac{1}{2}u^2-\frac{1}{2}v^2$.
So, using this inequality three times, it is:
$$-x_1x_2-x_1x_3-x_2x_3\ge-\frac{1}{2}x_1^2-\frac{1}{2}x_2^2-\frac{1}{2}x_1^2-\frac{1}{2}x_3^2-\frac{1}{2}x_2^2-\frac{1}{2}x_3^2=-x_1^2-x_2^2-x_3^2$$
$$\implies x_1^2+x_2^2+x_3^2-x_1x_2-x_1x_3-x_2x_3\ge0 \implies f(x_1,x_2,x_3)\ge0$$
For each $(x_1,x_2,x_3)\in\mathbb{R}^3$, and since $f(0,0,0)=0$ this means that $(0,0,0)$ is a global point of minimum in $\mathbb{R}^3$ for $f$.

Minimizing a function in $\mathbb R^3.$


Examples of norms essentially different from $p$-norms

Question: I'm looking for examples of norms that can be applied to finite-dimensional vectors but are not just $p$-norms or trivial variations of them. The ones I've found - the norms in James' space or Tsirelson's space - only make sense for infinite dimensions.
To be more precise, I'm looking for norms which are not of the form $\|v\| := \|Av\|_p$ for some positive definite matrix $A$, or $\|v\| := \lambda \|v\|_p + (1-\lambda)\|v\|_q$.
The only example I've found so far is the norm defined as $$ \|v\|^{(k)} := \sum_{i=1}^k \max_j{}^{\!(i)} |v_j|,$$ where $\max^{(i)}$ is the $i$th largest element.
There must be more interesting norms. Any ideas?
Comment: Have you considered the various [matrix norms](https://en.wikipedia.org/wiki/Matrix_norm)? Matrices are finite-dimensional vectors, after all.
Comment: Yes, I have. But to get an interesting matrix norm you'd need to reshape the vector into a rectangular matrix, which will only work if the dimension is not a prime number, or if you pad the vector with zeroes until the dimension is nice. I was hoping for something less contrived.
Answer: A norm is uniquely determined by its unit ball, and conversely, you can define a norm to have any unit ball you like. The construction goes like this. Let $K\subset \mathbb{R}^n$ be a closed, bounded, convex, and symmetric set ($x\in K$ if and only if $-x\in K$). Define
$$\|x\|_K = \inf\{\lambda > 0 \, |\, x \in \lambda K\}.$$
This is called the Minkowski functional, and $\|\cdot \|_K$ is a semi-norm. If you also assume $K$ contains an open neighborhood of the origin, then $\|\cdot \|_K$ is a norm, and the unit ball for the norm is exactly $K$.
So basically you can select any $K$ (within reason) and define a norm for which $K$ is the unit ball. Every norm can be constructed in this way, so it is very general and generates "new" norms that are not just $p$ norms.
As an example, let $X_m$ be a collection of $m$ independent and identically distributed random variables $\mathbb{R}^n$ with a Lebesgue density, and set
$$K_m = \text{ConvexHull} (-X_m \cup X_m).$$
Then define the norm $\|x\|_{K_m}$. This is a norm with a unit ball that is a random convex polytope (provided $2m \geq n+1$).
A concrete example is the $n$-dimensional polytope with vertices of the form $$\frac{1}{\sqrt k} \sum_{i=1}^k s_{\sigma(i)} e_{\sigma(i)}$$ for all $k \le n$, all signs $s$ and permutations $\sigma$. It has $\sum_{i=1}^n {n \choose i}2^i$ vertices.
Comment: @MateusAraújo Jeff answered *exactly* your question as it was formulated above. Even more, he gave you a tool to find *all* norms. Which are "essentially different" or "interesting" is up to you. Almost all norms described this way are unlike the $p$-norms, e.g. taking as unit circle a regular polygon on even many sides. Either you edit the question or you post a new qustion with your actual restriction. Because I see no way to answer this one other than Jeff did.
Comment: I suppose then you do not consider $\|x\|_p:= (\sum |x_i|^p)^{1/p}$ an example of a norm until it is instantiated by choosing a value for $p$?
Comment: Can you add a concrete example of an interesting $K$?
Comment: There are an infinity of possible examples; I don't know what you find interesting. I added an example where the unit ball is a random polytope.
Comment: Yes, there is an infinity of possible examples, this is exactly the problem. "Interesting" is left for you to decide, but I had something more concrete in mind than a random polytope.
Comment: Make it concrete by selecting the points $X_m$ yourself; anything is fine as long as they are affinely independent. Or choose your favorite convex set and off you go.
Comment: Of course I could do that, and end up with a norm that is a pain in the ass to evaluate, and really hard to prove anything about.
Comment: You did not specify you wanted a norm that is easy to evaluate. And what do you want to prove about it? The Minkowski functional is a useful tool in functional analysis precisely because it is easier to use in certain proofs.
Comment: The Minkowski functional is great, thanks for telling me about it. What I'm complaining about is the generalness of $K$. Maybe it is a cultural difference, what physicists think count as a nice example, and what mathematicians think count as a nice example.

Specifically, I wanted to find a nice norm for which the theorem by Bohnenblust discussed [here](https://mathoverflow.net/questions/292322/which-norms-on-vectors-can-be-consistently-decomposed) does not hold, and more generally explore norms that could provide alternatives to the Born rule.
Comment: @M.Winter, if you want to be pedantic, Jeff didn't provide a single example, just a general strategy to generate examples. One does need to instantiate it. Contrast with Felix Klein, which did write out two well-defined norms (although he neglected to prove that it was not of the undesired form.).
Comment: @MateusAraújo Here is an *explicit* example. Let $K$ be a hexagon (e.g. centered at the origin, side length $1$, vertices on the $x$-axis). Then $\|x\|_K := \inf\{\lambda > 0 \, |\, x \in \lambda K\}$ is a formula for such a "different" norm. Since $p$-norms do not have hexagonal unit circles, it's even "essentially different". Do you need anything else?
Comment: Yes, @M.Winter, this is all I want. It is easy, just a couple of lines that need to be added to the answer. Nothing to fight about. Jeff, if I edit your answer to include an explicit $n$-dimensional polytope will you accept the edit?
Comment: Sure, go ahead.
Comment: Thanks, it's there.
Answer: Take any norm $\nu$ on a function space and then define
$$\Vert(a_1,\ldots,a_n)\Vert=\nu\left(t\mapsto\sum_{k=1}^na_kt^{k-1}\right).$$
For example
$$\Vert(a_1,\ldots,a_n)\Vert=\sup_{t\in[0,1]}\left\vert\sum_{k=1}^na_kt^{k-1}\right\vert$$
Or
$$\Vert(a_1,\ldots,a_n)\Vert=\int_{0}^1\left\vert\sum_{k=1}^na_kt^{k-1}\right\vert \omega(t) dt$$
For some positive weight $\omega$.
Comment: I haven't done a proof, but I'm pretty sure both your examples reduce to $\|v\|=\|Av\|_p$ for some positive definite matrix $A$.
Comment: I doubt this is the case, especially with the first example where $\nu$ is arbitrary.
Comment: I think you missed the "both of your examples" part of my sentence.
Comment: I still doubt either example is in the form you suggested. If you think it is, give a proof.
Comment: Well, Felix Klein is the one proposing this as an example of a norm which is not of the undesired form, I think the burden of proof lies with him.
Answer: I still would like to have some more "natural" examples of such norms, specifically those with smooth and permutation-symmetric unit balls. Using the Minkowski functional, as explained by Jeff, allows me to define a norm from any convex body which is closed, convex, and symmetric. Playing around I found two nice unit balls. One is
$$ K_\text{exp} = \{x \in \mathbb R^n: \frac{1}{e+n-1}\sum_{i=1}^n e^{x_i^2} \le 1\},$$
for which it is really difficult to calculate the corresponding norm $\|\cdot\|_\text{exp}$ for any non-trivial vector. The cases I could solve analytically are
$$\|1^{(n)}\|_\text{exp} = \frac{1}{\sqrt{\log(1+(e-1)/n)}}$$
where $1^{(n)}$ is the vector of all ones,
and for the vector $(1,\sqrt{2})$ we have
$$\|(1,\sqrt{2})\|_\text{exp} = \frac{1}{\sqrt{\log(-\frac12+\frac12\sqrt{5+4e})}}.$$
The other unit ball is
$$ K_\text{log} = \{x \in \mathbb R^n: \frac12\prod_{i=1}^n(1+x_i^2)\le 1\},$$
for which I also couldn't get a general formula for an arbitrary vector. For the vector of all ones we have
$$\|1^{(n)}\|_\text{log} = \frac{1}{\sqrt{\sqrt[n]{2}-1}},$$
and for an arbitrary 2-dimensional vector $(x,y)$ we have
$$\|(x,y)\|_\text{log} = \frac1{\sqrt2}\sqrt{x^2+y^2+\sqrt{x^4+6x^2y^2+y^4}}.$$


Is there a way I can get a string value out of an enum in C#

Question: I have the following code:
public enum RoleType
{
    Default = 10,
    Guest = 20,
    User = 30,
    Admin = 40,
    Super = 50
}

Is there any way that I could get have some kind of toString method in the enum that would give me the strings "Default", "Guest" .. etc    I don't mind to hard code these in one by one or even have a dictionary with the values hardcoded twice inside the enum. I would just like to keep everything self contained inside of my enum.
Answer: How about ToString()?
Console.WriteLine(RoleType.User);

> User

Console.WriteLine(RoleType.User.ToString());

> User

Answer: Use RoleType.Guest.ToString()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public enum RoleType {
        Default = 10,
        Guest = 20,
        User = 30,
        Admin = 40,
        Super = 50
    }

    class Program {
        static void Main(string[] args) {
            Console.WriteLine(RoleType.Guest.ToString());
            Console.ReadLine();
        }
    }

Answer: string str =Enum.GetName(typeof(RoleType), obj);

obj should be the value you want the name for
Comment: I think the method name is `GetNames`
Comment: I didn't expect this existed. Is there a way I can get all of the names and values? Sorry it's a bit out of the scope of the question.
Comment: @Shahar You're right; I misread the question and thought the answer to be `GetNames`
Answer: string s1=Enum.GetNames(typeof(RoleType), object);