SimpleDateFormat cast String não consulta no banco

Question: Estou fazendo um aplicativo colaborativo para android, portanto, fiz um servidor em PHP, e envio os dados para este servidor.
Para uma determinada consulta preciso passar uma data, a partir de um Date Picker, eis o código:
String myFormat = "dd-MM-yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
et_data.setText(sdf.format(myCalendar.getTime()));
String data = sdf.format(myCalendar.getTime()) +"";

A variável data é passada para o servidor, porém no servidor ele não está interpretando como texto.
Mas se eu setar a variável data como:
String data = "12-02-2018";

Funciona normalmente. O valor que chega no servidor é este mesmo, e o type também é String.
Alguém sabe o que pode ser?
Comment: Não deu pra entender seu problema, testei seu codigo e está funcionando, ao menos como imagino que deveria, ja que nao esta claro seu problema: https://ideone.com/ntrhqD
Comment: Pois é , pra mim o código parece certo. Quando recebo no servidor PHP ele não interpreta isso -> (String data = sdf.format(myCalendar.getTime()) +"";), como uma String.
Comment: Entao o problema nao é no lado do java.
Comment: Como está a receber isso no lado do servidor em PHP ? De que forma é que faz o "envio" da informação ?
Comment: Você disse que se setar a variável como `12-02-2018` funciona. Mas o `SimpleDateFormat` que vc criou usa `dd-MM-yy`, que só imprime o ano com dois dígitos. Tente trocar para `dd-MM-yyyy`
Comment: Outro detalhe é que o método `format()` já retorna uma `String`, e concatenar com a `String` vazia (a parte no final `+""`) é redundante e pode ser removido. Então ficaria somente `String data = sdf.format(myCalendar.getTime());`
Answer: Altere seu format para dd-MM-yyyy porque se colocar com 2 y somemente ele vai pegar o valor literal e não numérico.
Ex:
String myFormat = "dd-MM-yyyy";


Bouncy Castle and WebPush: NoSuchMethodError: org.bouncycastle.math.ec.ECCurve$Fp

Question: I'm trying to extend and existing web app (I don't have control of) with a jar extension to add push notification feature. I tried to follow the instructions here:
https://github.com/web-push-libs/webpush-java/wiki/Usage-Example
But when BouncyCastle comes into play I'm getting the following exception:
java.lang.NoSuchMethodError: org.bouncycastle.math.ec.ECCurve$Fp.<init>(Ljava/math/BigInteger;Ljava/math/BigInteger;Ljava/math/BigInteger;)V

while processing nl.martijndwars.webpush.Utils.loadPublicKey(String) method.
    public static PublicKey loadPublicKey(String encodedPublicKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPublicKey = Base64Encoder.decode(encodedPublicKey);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);
}

The return-line then throws the exception.
The spi instance of the keyFactory is "org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi$ECDH@5a15f280" which also seems right...
Im using the jar via maven. "Luckily" the parent web application brings BouncyCastle on it's own in Version 1.54. That's the dependency in the web apps pom.xml
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.54</version>
        </dependency>

Which actually should exactly match the library's version (e.g. https://github.com/web-push-libs/webpush-java/blob/master/build.gradle)
And when I call java.security.Security.getProviders() I'm getting a list that already contains 'BCFIPS version 1.01, BC version 1.54', which is because the parent application already provides it during runtime.
When checking out the sources (http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.53/org/bouncycastle/math/ec/ECCurve.Fp.html for instance) the constructor exists.
I also tried to remove and add the BouncyCastleProvider from java.security.Security before executing the code.
EDIT#1:
I've made some progress in understanding the issue. I noticed that the web-server jre has a external library (bc-fips-1.0.1.jar) which seems to bring another implementation of org.bouncycastle.math.ec.ECCurve$Fp. This jar also seems to be the reason for the 'BCFIPS version 1.01' security provider.
By calling keyFactory.generatePublic(pubSpec) is seem that the KeyFactory somehow (classloading issue I guess) uses the other version ECCurve$Fp that really does not have the constructor from the error message.
EDIT#2:
I've debugged a while and could proof my theory. The WepAppClassloader picks the class from the lib-folder (which is the wrong one). Now I've tried somehow to preload the correct class for the right jar. But this does not seems to work.
EDIT#3:
The final solution for me was to repackage the bouncy castle lib. Not nice but I had no ideas anymore.
Answer: The problem is that you have two SecurityProviders from BouncyCastle in your distribution - the FIPS certified version, as well as the regular version. You need to remove the FIPS version if you want to use the specifc method that's throwing the exception.
Once you remove it, that part of the code will work fine, but its possible that other parts that are dependent on the FIPS certified library may not work. Ideally, you should be using only one or the other JAR - not both; so you may need to refactor your code for what you want.
Comment: The problem in my case was, that I didn't have control of the application itself but of the extension. So I could not remove the FIPS lib. Repackaging is not the nicest way but so I could use my BC version and left the application itself untouched.


Accuracy of numbers provided by the "Statistics Advanced" module?

Question: We use modules Google Analytics and Statistics Advanced, in Drupal 6. It is clear from the numbers that they provide very different readings.
Can anyone give any accuracy analysis for the Statistics Advanced module, perhaps by comparison with Google?
Answer: As it relates to Statistics Advanced, you may want to take into account some of the options mentioned on its project page. Such as:

Only track 'unique' views of content: If you keep viewing a node over and over again, the "x reads" counter won't increase each time. This is applied on a per-user basis as well as a per session id for anonymous users.

Refer to the project page for other options mentioned there.
Disclosure: I'm the (new) maintainer of Statistics Advanced.


Created my own viewsContainer - can I include views from other viewsContainers?

Question: We are exploring creating our own viewContainer for VS Code in a new extension and would like to re-use views from other containers, such as the Resources tree, Outline, and others from other extensions. Is this possible?
I was unable to find the view ID for the Outline view, for example, but would hope I could do something like...
"contributes": {
    "viewsContainers": {
        "activitybar": [
            {
                "id": "custom-activity",
                "title": "My Uber-activity",
                "icon": "resources/custom-activity.svg"
            }
        ]
    },
    "views": {
        "custom-activity": [
            {
                "id": "vscode-resources",
                "name": "Resources"
            },
            {
                "id": "vscode-outline",
                "name": "Outline"
            },
            {
                "id": "my-fancy-view",
                "name": "New View"
            }
        ]
    }
}

Is this possible? Is there a list of published IDs for established views in the VS Code environment that we could reference and re-use?
Answer: That's an interesting question. According to the sources, the ID of the outline view is simply "outline":
export const OutlineViewId = 'outline';

Well, ok, let's try that...
"views": {
    "custom-activity": [
        {
            "id": "outline",
            "name": "outline"
        }
    ]
}

Ok, let's click our custom view container... oh.

Erm, yes, I think it's fair to say that this is currently not supported. I've reported this as an issue here.
Comment: Thank you @Gama11 for testing and reporting that! We'll keep an eye on it.


Why does G# sound right when my melody is in C major?

Question: I composed the following melody using notes from the C major scale. In the third bar a G# (Ab) seemed a natural choice to complete the loop, but I don't understand why.
G# is not in C major nor its relative minor scale Am. It is one semitone down from A, so it seems to lead back to the Am scale naturally. What is the reason?
Edit : Here is the corrected cleaned up score
[![Original melody][1]][1]
Comment: One little off-topic observation: the first three measures have 4.5 beats in them (four eighth notes = two beats; one half note = two beats; plus one 8th note). If you changed the half note to a dotted quarter (1.5 beats) it would fit nicely.
Comment: Yeah, the recording perfectly uses dotted quarter notes. If you sing along with it, "1 and 2 and 3 and 4 and," you'll find that the F in the first bar occupies "3 and 4," and then the D 8th note takes up the "and" that comes after "4."
Comment: Thanks Andy, what you suggest sounds more correct. Here is a recording of what I was trying to transcribe. I was in a dilemma in that I wanted the half note to play to the end of the bar but I needed the eighth note to play on the « 3and ». If I understand correctly, notes are always sequential so it is impossible to overlay the eight note, I must instead shorten the half note. https://soundcloud.app.goo.gl/bkCQXSyM6dzSg1Tn6
Comment: Another little off-topic nitpick: if a note has its stem (the vertical line) pointing down, the stem is on the left and the head (the dot) is on the right, like the first four notes. The other way looks a bit awkward. (You also don't need to repeat the sharp in the last measure — those signs work up to the end of the measure.)
Comment: @Ramillies - I'm sure some notable (sic) composers preferred OP's way as well.
Comment: @phoog - perhaps it's done more by sinistral composers (here we go again...)?
Comment: While normally a conversion to ABC isn't cause for editing, I voted in favour of approving this one since it actually fixes some notation mistakes that distracted from the question's intent.
Comment: @Tim it was common to do it that way in some places during the 18th century, and I think I've seen some printed music from the 19th century like that as well, but it has been nonstandard everywhere for well over 100 years as far as I know.
Comment: @user45266 sorry but I rejected your edit. It is important for me as the originator of the question to keep the GIF of my flawed original hand written score and the corrected one I created using the Symphony app after receiving the very helpful comments above. Please do not delete these again.
Comment: @acidtrancejunkie It wasn't user45266's edit; they only voted to approve. I am the one who edited it to convert to ABC.  The point of the question seemed to be about harmony, not notation so I made the notation easier to read.  I'm not going to bother with further edits to your question, but I might suggest at least cropping off the interface clutter from the screenshot of your Symphony score when inserting.  Might I also suggest not sharing on a platform with a CC-BY-SA license if you need to retain control.
Comment: @Theodore understood, thanks. (Sorry to user45266 !) I cropped the score photo as much as my phone would allow vertically. Ok for licensing this time, thanks, I will keep this in mind.
Answer: I would argue that your melody may not be in C major at all. C major and A natural minor share the same pitches, and your melody is constructed precisely in such a way that it can exist both in C major and in A minor!
You might think, "Well, the first measure emphasizes C and E, which are both members of the C-major tonic triad." But they're also the third and fifth of A minor! So depending on the harmonic accompaniment you create, your melody may be in A minor the whole time.
The G♯ is the leading tone of A minor; it's what helps clarify A as tonic, whereas the G♮ (what we call the "subtonic") lacks the same kind of pull upwards towards tonic. The use of a raised scale-degree 7 to create the leading tone is very common in minor keys.
Lastly, I'd recommend you doublecheck some of your rhythms. Your half notes in each measure technically create measures of nine eighth notes; these should probably be dotted-quarter notes instead.
Comment: I agree 100%.  To me, it certainly feels like Am the whole way through.  In the first bar, an Am to Dm transition would be a more natural harmony than a C to F transition.
Comment: It feels like Am because of the last measure. Changing G# in G♮ and ending in C rather than A makes a perfect fit for C-major.
Comment: @DawoodibnKareem to me, it sounded like C major the first time through until I got to the end of the next-to-last measure.  After that, the beginning seems like A minor, also, but depending on what else happens in the piece it could indeed be melody in C major with an intermediate cadence in the relative minor.  If you use G naturals and change the last note to C, and then play through that a couple of times, do you still think of the first couple of bars in A minor?  Context matters.
Comment: Yeah, I can't bring myself to put anything other than Dm in the left hand for the second half of bar 1.  If I make the change that you (@phoog) suggested, it feels like it's modulating from Am to C.  I'm wondering whether it's because this melody reminds me of some other piece of music that I can't actually place.
Comment: @DawoodibnKareem ok, but that D minor chord doesn't stop it from being in C major: `C Dm G(7) C ...`.
Comment: True that!  OK, it feels like Am to me for some unknown reason that I have failed to enunciate then.
Answer: You started in key C major, and you've modulated into key Am, its relative minor.
True, there's no G♯ note in key C major, but key A minor has three slightly different incarnations, when written in scalar form, two of which actually do have that G♯.
Those notes just before the last note, A, all work with the chord E, which most times in music will lead to A. It's called the dominant of A, and sounds more convincing with that G♯ rather than G♮ to point the way to A. Play it with G♮, and it doesn't sound anywhere near as good, does it?
Don't be fooled, as so many are (and I was!) into believing a piece in a particular key will only contain notes from the scale of that key. true, pieces will be 'safer' when that happens, but can become quite banal. By using notes out of the key, colour is added. Thus those notes are called chromatic - funnily enough having a close connection to colour...
Comment: It seems that with the right harmonization, this could be entirely in A minor.
Comment: Thank you Richard,Aaron and Tim for your comments. It took me a while to process. I now understand that my melody works because I was using a leading tone, the G# of harmonic minor scale of A to return to the tonic of Am.
I went through all major and minor scales and it seems the 7th is a leading tone (1 semitone below the tonic) in ALL major scales, but in NONE of the natural minor scales, and so requires using the harmonic or melodic minor scales to obtain a leading tone.
Comment: @Theodore - ye, it could be easily. We won't really know until the last bar gets written - and my money's on key C!
Comment: @LukeSawczak - I do! C major and A minor are different keys, even if they (often) use the same notes, so yes, modulate.
Comment: Does one really say "modulate" between a key and its relative minor? (Genuine ignorance on my part.) Interesting.
Comment: @acidtrancejunkie The key of A minor has no different incarnations.  There are various incarnations of the minor _scale._  The harmonic and melodic minor scales exist as a (somewhat awkward) explanation of the fact that people use leading tones in minor keys by chromatic alteration of the seventh scale degree.  Saying that you have to use one of those scales to have a raised leading tone is more or less backward.  In fact, this question is good evidence of that.
Comment: I agree that this makes the most sense as a modulation from C to Am, rather than being in Am the whole time. The two chord progressions that I like best for this melody are: (1) C, F, G, C, Am, E, Emin7, Am; or (2) C, F, G, Am, F, Dm, Emin7, Am. Both transition from C to Am.
Answer: Although A minor does not natively include G#, it is common practice to use G#, because it is the leading tone in A minor (and major). That is, it "leads" the ear to A, just as you've described.
This idea is also discussed in When to deviate from scale?
Technically, what you've composed is called a sequence, a pattern of sounds that is repeated on different pitches. In this case, your pattern modulates (changes key) to A minor. So even though the song itself is in C major, it is visiting another key, which is just fine.
Sequences of the type in your composition are discussed in How are melodic sequences used?
Answer: I'm a newbie at this stuff but I'll take a crack at explaining why it sounds good to me. I think we can simplify the melody by reducing the n,n+1,n+2,n eighth notes (like C D E C) patterns to the first note n and removing the trailing eighth notes; brief or unrepeated notes make less of an impression. So then we're left with C F|B E|A D|G# A. We can break this down into adjacent pairs to look at harmony and dissonance:
C  F  perfect 4th
F  B  tritone (dissonant)
B  E  perfect 4th (resolution)
E  A  perfect 5th
A  D  perfect 4th
D  G# tritone (dissonant)
G# A  semitone back to A (resolution, D was not long ago)

So the adjacent pairs were seesawing back and forth between dissonance and harmony.
You could have made this more of a C scale if you had continued the pattern C F|B E|A D|G C, but play it out and it feels like it's too quick and less interesting without the G# dissonance and the resolution.
Answer: Quick, general answer:  Because chromatic notes and chords are a thing.  A very commonly-used thing.  You don't have to stay in the scale.
Longer answer, more specific to this instance:
You have fallen into the trap of assuming that the 'Natural minor' scale is the ONLY form of minor scale.
Until quite recently, standard teaching was that the Harmonic minor scale was the norm, sometimes modified into the Melodic minor.   But they both used the sharpened leading note when ascending, which enabled a major dominant chord, a central feature of Common Practice harmony.  (If Harmonic minor, Melodic minor mean nothing to you, there are plenty of online resources for basic theory, I won't try to spell it all out here.)  In fact, when trying to determine whether a piece had strayed into the relative minor key, the rule of thumb was 'spot the sharpened 7th'.   When a piece that starts in C major starts getting G sharps, that's a pretty good clue that we might be visiting A minor.
The Natural minor scale, with its flat 7th note, was a poor relation, mostly found in folk music.  Natural, with its modal flat 7ths and lack of proper dominant chords only suited folk songs.    Don't get annoyed, but there's a certain truth in that.  A musical form longer than a simple song ("all you can do with a folk song is play it again, louder") will probably use different keys as a structural device.  And you get to new keys through dominant-tonic relationships.
Comment: Modes - Ionian and Aeolian, may be worth a mention here.
Comment: @Theodore I didn't really analyse the words that closely!  But see my extended answer.
Comment: By "poor relation" do you mean "indigent cousin" (a class distinction) or "inferior version" (a quality distinction) or both?
Answer: Your melody's inherrent harmony (the one you imagine when you hear it) is
C F | G C | a d | E a (lowercase indicates minor chord)
This is more natural than having e a in the end, which would not have nearly as strong of a gravity towards the final note. You can also try A d | E a (i.e. using c# in bar 3), it will get yet a different feel, and whoa, you'll use c# in a piece in C major / a minor!
The bit is actually we well thought out -- not sure if it's an intention or a coincidece, the piece is just an ornamentation of c f | b e | a d | g# a, so bar 1 doesn't have a leading note, meaning the resolution of C > F is not as strong as in bar 2 where a third is used (b), but it's not properly resolved to a tonic (it should be resolved to c not e). Then the second part is the same motif, just in the parallel tonality and properly resolved to the tonic. Very cool!
Also, while bars 1 and 3 don't have as strong of a lead, they still contain the third of the dominant in the ornamentation, giving quite a hint!
Comment: I think you missed my point, which maybe is more clearly stated as:  The preference for a dominant - tonic resolution in harmony is *culturally-conditioned* and not *[inherent](https://en.wiktionary.org/wiki/inherent#Adjective)* to a melody (even one so obviously within the realm of common practice).
Comment: @Theodore You're free to assume that it's conditioned, but I don't agree with that assumption :-) But it's good to know that this is the point of disagreement as I was slightly unsure what you meant by your comment. Now it's clearer...
Comment: The harmony you suggest initially does work, but I don't think you could call it inherent*.  I could just as easily hear:  a G | E a | F d | E7 a
Comment: @Theodore You _could_ in theory, but the longer you'll keep deciding which one is more natural, the more you'll lean towards the variant with V > I for bar 1. And for bar 2, yes, if the whole second part wasn't a third lower and if you didn't mind having the leading voice lead to a fifth without ever seeing the first or third, then yes, you can surely see it that way. The point is: you can find many harmonies that fit a certain piece of melody or explain it, but not all of them will sound equally natural.
Comment: You can equally explain the last bar as `E75-/Bb a` and you'll get a nice (and somewhat baroque) explanation of having that piece with `g` instead `g#` by borrowing something from the phrygian mode. Or if you like, you can change the harmony completely, use `g a bb g a` and consider `C7 F` as the underlying harmony. The possibilities are plenty, but the question is about explaining why `g# a b g# a` "feel the best", and that's what I do.


Como disponibilizar um arquivo para dowload inline em html?

Question: Eu queria criar um link pra um dowload no meu HTML, mas não queria guardar este conteúdo em um arquivo separado, mas no próprio html.
Em imagens tem como fazer algo assim

Será que para links também é possível?
Comment: Você está querendo converter um aquivo para base64 e enviar ele junto ao HTML? Assim ao clicar no link o usuário irá baixar esse arquivo? Se for não aconselho, pois seu HTML irá ficar pesado e irá demorar muito para carregar, sem saber se a pessoa quer ou não baixar o arquivo.
Comment: Isso, mas não estou preocupado com o tamanho do arquivo, ele é pequeno
Comment: Lembrando, pra quem for aplicar as soluções abaixo, de setar um **Content-Security-Policy** adequado, permitindo `data:text/html` (ou outro mime mais adequado) no `default-src`
Answer: Você pode utilizar o MIME-type data:text/html
Renderizar o código HTML quando clicar no link:
<a href="data:text/html;charset=utf-8,
pt.stackoverflow
">Clique aqui

Exemplo no JSFiddle

HTML5
No HTML5 a tag ganhou um recurso de download.
Fazer download do código HTML quando clicar no link:
<a href="data:text/html;charset=utf-8,
pt.stackoverflow
" download> Clique aqui

Exemplo no JSFiddle
Seria isso o que você quer?
Mais informações sobre DATA URI aqui.
Sobre o recurso do download na tag  vi aqui.

Nota: Na maioria dos navegadores o data: é considerado uma origem separada, então em alguns contextos é necessário setar um Content-Security-Policy que permita data:text/html (ou outro mime mais adequado) como fonte confiável no default-src, para que não haja bloqueio do conteúdo.
Comment: +1 Muito massa essa resposta. :)
Answer: Basta fazer isso:

Answer: Você pode usar um atributo do HTML5: download="pagina.html"
Exemplo:
<a download="pagina.html" href="data:text/html;charset=utf-8,
conteúdo/h1>">Clique aqui

http://www.w3.org/TR/html/links.html#downloading-resources
https://stackoverflow.com/questions/6468517/force-download-of-datatext-plain-url/20282249#20282249


No module named 'pandas' - Jupyter, Python3 Kernel, TensorFlow through Docker

Question: I have a Docker container running from tensrflow with Jupyter (Python 3 Kernel) image: erroneousboat/tensorflow-python3-jupyter
This works great and I can access the jupyter notebook from
http://DOCKER_IP:8888
My only issue is that pandas library is not installed. So, I tried to install it on my own. I opened up the docker quickstart terminal and ran:
docker exec CONTAINER_ID apt-get update
docker exec CONTAINER_ID apt-get install -y python3-pandas

The installation succeeds, and yet I still get the ImportError: No module named 'pandas' when I try to import pandas in the jupyter notebook, like so:
import pandas as pd

I also tried installing pandas to the image rather than just my container by:
docker run -it erroneousboat/tensorflow-python3-jupyter /bin/bash
apt-get update
apt-get install -y python3-pandas
exit

Still, in my jupyter notebook, pandas is not recognized. How can I fix this? Thank you!
Comment: have you tried `pip install pandas`?
Comment: I have not. Just did and it worked! If you make this into an answer, I'll select it - thanks! Also, is there a reason why pip install would work and a system-wide install would not?
Answer: pip install pandas will install the latest version of pandas for you.
Based on your tags python-3.x, I assumed pip belongs to your Python3 version, if you have multiple python versions installed, make sure you have the correct pip.
Comment: It's weird that anaconda told me this was already installed but using `pip install pandas` fixed the problem in jupyter notebook


How to make jQuery methods work in a for loop?

Question: I know I can use the jQuery .each() function (and it works fine), but the performance is too sluggish. So I want to use a for loop and have the jQuery methods available inside it.
For example:
var anArray = $('#somediv').children(); // it has a lot of children
for(i=0;i<anArray.length;i++) { // or for(i=anArray.length;i--;)
  anArray[i].addClass('sample_class'); // and a bunch of other stuff
};

Right now the browser throws this error:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'addClass'
Think it had something to do with the jQuery wrapper $()
I know I read the solution somewhere a while ago, but I'm just unable to retrace it.
Answer: Exactly , wrap it , because they are DOM elements and actually has no addClass method  :
$(anArray[i]).addClass('sample_class');

Reference: http://api.jquery.com/children/
Comment: Seems like someone took the time to do the test: http://jsperf.com/addclass-v-classname
Comment: Gosh, should have tried it on every action in the for loop; thanks for quick reply. +1  Performance-wise, is it better to use the jQuery wrapper, or use the native JS .className? I suppose the native method?
Comment: @Tyblitz you know , you'll feel some difference  if you have hundreds of hundreds dom nodes. but in any case seems like `$` wrapping is a little bit expensive operation..
Answer: You could also use the equivalent addClass for Javascript
anArray[i].className = "sample_class";

Comment: oh really? Thanks for this, thought Js only allowed for id manipulation; +1


Cleaner syntax for calling a function on condition

Question: I find myself doing the following kind of snippets a lot
if(bar != null)
   foo(bar)     // That is, pass in object 'bar' to function 'foo' if bar is not null

EDIT: The foo function is from an API and I don't have access to it's code. Essentially the API's function expects a non-null input.
Is there a cleaner C# way to do this? Or am I doing something architecturally incorrect if I find myself doing this a lot?
Apologies if this is a repeat, I can't seem to find the right words for the search.
I have tried to use the new coalescing operator to achieve this, but that can't be used to call a function. Not sure if ternary operators can be used to achieve this either.
I expect there to be a one line way of doing this. Kind of like
bar ?? foo(bar) // That is run foo with bar when bar is not null.

Comment: What's "unclean" about an "if/else" statement?!?
Comment: There's a cleaner way, try using aggregating functions like `TrueForAll(array, predicate)` with collections, or try LINQ.
Answer: You may null check inside the foo method:
void foo(object bar)
{
    if(bar == null) return;
    //your lines of code
}

then you can just run as:
foo(bar);

Comment: I guess I should have made that clear. The foo function is from an API that I don't have access to. Essentially the API's function expects a non-null input. Editing my post ... Thanks!
Comment: the you just have to go with your if statement
Answer: You can use a Ternary operator for instance that would look something like this:
bar != null ? foo(bar) : * ;

where at * you would insert the statement you would like to execute if bar == null.
Comment: I guess if I didn't have anything to execute when bar == null, i could just do

```
bar != null ? foo(bar) : return;
```

That's one way of doing it I guess. Thanks!
Comment: @KishoreVenkateshan  You can leave it open like this `bar != null ? foo(bar) : ;` or if you instantly want to return use the return keyword like in your example.
Answer:
am I doing something architecturally incorrect if I find myself doing this a lot?

Perhaps.  You should generally know whether your variables can ever be null, and omit the checks.  C# 8 is introducing a feature to help you declare, verify and enforce that a reference can not be null: Nullable Reference Types.
Comment: Ah this is actually better! Thanks for pointing me to this. I will make sure to read further about the new C# 8 features.


Unlimited values field in Drupal 7 - how to show extra field in page.tpl.php

Question: I know how can I retrieve the first file name
<code>$fileupload = $node->field_fileupload[$node->language][0]['filename'];
</code>
but how can I retrieve the other unlimited file names
Answer: The best solution would be to run a foreach:
<code>foreach($node->field_fileupload[$node->language] as $fileupload) {
  echo $fileupload['filename'];
}
</code>


In Chopin Marche funèbre, measure 19, on right hand, is the A flat played once or three times?

Question: In Chopin Marche funèbre, measure 19, on right hand, is the "A bemol" played once or three times ?
Is the "C" played three times ?

Adding also Gymnopédie 1 from Satie :

It seems that here, the F# is not played 4 times but only once. But they use exactly the same notation as the case of Chopin Marche Funèbre.
Comment: That's not the exact same notation between the Gymnopedie and the Funeral March. The Gymnopedie doesn't have one arc spanning multiples of the same note - it has separate arcs, and that makes all the difference.
Comment: @Aaron I see that now, I initially read the question as if it was a confusion on Ab once and A two times or not. I retracted my vote.
Comment: ...and honestly, given the colliding voices of the Gymnopedie, I'd actually play that tied F# *four times* anyway because the chords in the lower voice still want to sound out in full.
Answer: Three times.
Ties connect just two notes. Ties could be notated like A below.   Or, more likely, B - which might have been confusing.
But it wasn't written that way.  The A♭ is played three times.
Not an enormous  error in your playing to put right though!
Comment: This is of course not related to the issue, but that should be an Eb and a Db. Key signature is Bb minor.
Comment: Thank you. I was not aware that there were two sorts of this curved line.
Comment: @MathieuKrisztian as already mentioned elsewhere, the Satie is different from the Chopin because there is s a separate curved line connecting each pair of Fs in the Satie while the Chopin has a single curved line applied to three chords.  Furthermore, the Satie can only be notated with ties because each of the notes being tied takes up a whole measure.  Had Chopin wanted the A flat to be struck once and held for three beats, he would have written a dotted half note.
Comment: I added gymnopédie 1 example in question. It seems that here, the F# is not played 4 times but only once. But they use exactly the same notation as the case of Chopin Marche Funèbre. So is the notation evolving with the score ?
Answer: The Ab is played three times, as it is notated. The C is played twice (also as it is notated). Are you perhaps confusing the Slur with a Tie?
Comment: A mistake, but one that is easy to correct.  No disaster!
Comment: @MathieuKrisztian It is a small, not particularly significant part of the whole piece, so this can hardly be considered a disaster. And now you asked and thus know it better. After all life is about learning new things. And hopefully you've learned something about Slurs and Ties from this, which will pay off in many more cases than this small bit.
Comment: @MathieuKrisztian No, that is a Slur. A *Tie* is usually not allowed to span multiple notes and is set for each note of a chord separately.
Comment: From the image in the question, there are two ways you can tell that the line is not a tie. 1. It spans three chords. If all 3 A flats had to be tied, two ties would be needed: from the first to the second and from the second to the third. 2. It is reasonably close to the notes' stems but nowhere near the note-heads. The ends of a tie should be quite near the heads of the tied notes.
Comment: @MathieuKrisztian No the gymnopédie 1 does **not** use the exact same notation. This one does not have one bow over all F#s, but individual bows between each two F#s. This is necessary as one tie usually only ties two notes, not multiple notes.
Comment: hum... Are you sure ? There is a "tie" (a liaison of prolongation) ?
Comment: what you say is extremely important. I hope there could be somebody that would confirm the same answer of you, because somehow, since 6 months, I was playing only *once* the Ab. So it looks like I have done a disaster mistake since 6 months...
Comment: I added gymnopédie 1 example in question. It seems that here, the F# is not played 4 times but only once. But they use exactly the same notation as the case of Chopin Marche Funèbre. So is the notation evolving with the score ?


Geometric view of isomorphism between sets

Question: My studying of Commutative Algebra lead me to the following question (though not a strictly Commutative Algebra question) :
What is a (or the) geometric intuition of the isomorphism
$$\mathbb{R}[x,y]/(x^2-y,x-x^3+xy)\simeq\mathbb{R}$$
So $\mathbb{R}[x,y]$ is the ring of polynomials with variables $x,y$ and $(x^2-y,x-x^3+xy)$ is an ideal of $\mathbb{R}[x,y]$.
I would like to see an awnser for the spesific question for I have searched for 'geometric approaches' of isomorphisms in classics like the Atiyah MacDonald 'Introduction to Commutative Algebra' and in Algebraic Geometry material and I cannot figure out the idea. Really tough, I would like to know your mind considering geometric approaches of isomorphisms 'in general' (perhaps by giving an example that you have in mind, like the one above and of course, the more examples, the better). Also, any sources for further studying or links to previously related posts are welcome.
Comment: $(x^2 - y, x - x^3 + xy)$ doesn't look like a principal ideal to me. Did you mean "prime" or "maximal" perhaps? As regards intuition for your example, my intuition for it is purely algebraic: if an ideal contains $x^2 -y$, then $y = x^2$ in the quotient ring and we can forget about $y$, if it also contains $x - x^3 + xy$, then $x = x^3 -xy = x^3 - x^3 = 0$ in the quotient, so $x$ is $0$ in the quotient, which must therefore be either $\Bbb{R}$ or $\{0\}$. The elements of the ideal clearly all have $0$ for the constant term, so the quotient must be $\Bbb{R}$.
Comment: Oh god, I meant to say just "an ideal" and got ahead of myself because I've wrote down "principal ideal" so many times before. Thanks a lot, I edited my post. Thanks for the feedback too !
Comment: No problem - we all make mistakes!
Answer: The short answer: the curves $x^2 - y = 0$ and $x-x^3+xy = 0$ intersect in $1$ point, namely $(0,0)$. Correspondingly, the ring $\mathbb{R}[x,y]/(x^2 - y, x-x^3+xy)$ is isomorphic to $\mathbb{R}$ via the map sending $x \mapsto 0$ and $y \mapsto 0$. Note that

$\mathbb{R}$ has Krull dimension $0$, which reflects that the intersection (a point) is a $0$-dimensional variety; and
$\mathbb{R}$ is a $1$-dimensional $\mathbb{R}$-vector space, corresponding to the number of intersection points of the curves. (In general, the dimension is the number of points counted with multiplicity.)

The longer answer: Let $f_1 = y - x^2$ and $f_2 = x-x^3+xy = x(y - (x^2 - 1))$. To simplify things in the beginning, let's work over $\mathbb{C}$, which is algebraically closed. The vanishing locus of $\{f_1, f_2\}$ (or equivalently of the ideal $(f_1, f_2)$) is the set $\newcommand{\V}{\mathbb{V}} \newcommand{\C}{\mathbb{C}} \mathbb{V}(f_1,f_2)$ of points $(x_0, y_0) \in \C^2$ such that
$$
f_1(x_0,y_0) = f_2(x_0,y_0) = 0 \, .
$$
Given a point $(x_0, y_0) \in \mathbb{C}^2$, then $(x_0, y_0) \in \V(f_1,f_2) \iff (f_1, f_2) \subseteq (x - x_0, y - y_0)$; see here for a proof. By the correspondence theorem for ideals in a quotient, this means that $(x - x_0, y - y_0)/(f_1, f_2)$ is an ideal, and in fact a maximal ideal of the coordinate ring $\frac{\mathbb{C}[x,y]}{(f_1, f_2)}$. Moreover, all such maximal ideals of $\frac{\mathbb{C}[x,y]}{(f_1, f_2)}$ are of this form by the Nullstellensatz. Thus we get an algebro-geometric dictionary in which the points of the algebraic set given by $f_1 = f_2 = 0$ are in bijection with the maximal ideals of the coordinate ring $\frac{\mathbb{C}[x,y]}{(f_1, f_2)}$.
Over a non-algebraically closed field like $\mathbb{R}$, things are a bit more complicated. Maximal ideals of the coordinate ring $\frac{\mathbb{R}[x,y]}{(f_1, f_2)}$ don't correspond to $\mathbb{R}$-points of $\V(f_1,f_2)$, but instead to Galois orbits of $\mathbb{C}$-points. For instance, since there are no real solutions to the equation $x^2 + 1 = 0$, the maximal ideal $(x^2 + 1)$ of $\mathbb{R}[x]$ doesn't correspond to any real point. Instead it corresponds to the Galois orbit $\{i, -i\}$ of complex solutions to the equation, since $x^2 + 1 = (x-i)(x+i)$.
Fortunately in your example things are simple. The vanishing locus of $f_1 = x^2 - y$ is the parabola $y = x^2$, and the vanishing locus of $f_2 = x(y - (x^2 - 1))$ is the union of the $y$-axis and the parabola $y = x^2 - 1$. As you can see in the plot below, the intersection of these two algebraic sets is simply the point $(0,0)$.
$\hspace{2.5cm}$
Algebraically, one can see this by noting that $(f_1, f_2) = (x,y)$, since
$$
x = f_2 + x f_1 \qquad \text{and} \qquad y = f_1 + x^2 = f_2 + x(f_2 + x f_1) \, .
$$
Thus
\begin{align*}
\frac{\mathbb{R}[x,y]}{(f_1, f_2)} = \frac{\mathbb{R}[x,y]}{(x,y)} \cong \mathbb{R}
\end{align*}
where the last isomorphism takes $x \mapsto 0, y \mapsto 0$.
For similar connections between algebra and geometry, see this post and this post. For more on the algebro-geometric dictionary and how geometric properties are reflected in the corresponding algebraic structures, see this post.
Comment: I find the phrasing in your "short answer" to be misleading. It implies the dimension of the quotient will be the number of points in the vanishing locus, and that that's all you need to check. But this is not true even over an algebraically closed field, e.g. consider $\mathbb{C}[x]/(x^2)$. I also find the perspective on maximal ideals to be presented a bit backwards. The geometric reason the maximal ideals in the quotient are the points in the variety is because we have well-defined evaluation maps at those points given by restriction.
Comment: @JoshuaP.Swanson That is all you need to check as long as you count correctly. The dimension is exactly the number points counted with multiplicity, i.e., weighted by their intersection numbers. Consequently $\operatorname{Spec} \mathbb{C}[x]/(x^2)$ is more than a point—it's a fat point because the ring has nilpotents, which is reflected in the fact that it has dimension $2$ as a $\mathbb{C}$-vector space. Anyway, I'll add a remark about multiplicity.
Comment: @JoshuaP.Swanson I don't understand why you think my answer is "backwards". The OP has background in commutative algebra, so I began with the algebra. The algebraic reason there is a well-defined evaluation map at the point $(x_0, y_0) \in \mathbb{V}(f_1,f_2)$ is because of the containment of ideals $(f_1, f_2) \subseteq (x-x_0, y-y_0)$. Thinking of elements of the coordinate ring as regular functions on the corresponding algebraic set is certainly an extremely useful perspective, but to me the real answer to this question is just the picture of the curves.
Comment: Sure, some discussion of fat points makes it fine. It's just important not to oversimplify by ignoring that possibility. Perhaps the term "backwards" isn't quite right. What I meant was that the title of the question was "geometric view..." and the body repeatedly asks for geometric understanding, so using an algebraic approach when a geometric one is available didn't seem to me to be in the spirit of the question.
Comment: @JoshuaP.Swanson I still don't understand your objection. The first two sentences of my answer are: these two rings are isomorphic because these two curves intersect in a point. What could be more geometric than that? When I look at the isomorphism in the question, I see $\operatorname{Spec} \mathbb{R}[x,y]/(x^2-y,x-x^3+xy)\cong \operatorname{Spec}\mathbb{R}$, which is an intersection of plane curves on the lefthand side, and a point on the right.
Comment: The rest of the answer is just translating that observation into the language of commutative algebra using the dictionary afforded by the Nullstellensatz. In any case,  *de gustibus non est disputandum*.
Comment: I don't think you're hearing me. I'm not saying the bit about intersecting at a point is insufficiently geometric (though without mentioning fat points or similar anywhere it was potentially pretty misleading). My comments about "backwards" were confined to your use of maximal ideals. They're on the algebraic side of the algebraic/geometric dictionary. OP didn't ask for an algebraic and geometric comparison, they asked for a "geometric view". So, it seems reasonable to stay on the geometric side of the dictionary where possible, in particular at that place in your discussion using evaluations.
Answer: I think you might want to get a better idea of algebraic quotients in general, here's an answer of mine where I try to go in depth for a beginner: Ideal generated by $v\otimes v - \Phi(v)1$
Most introductions to category theory give a good overview of quotients; I'd suggest Emily Riehl's Category Theory in Context.
The core geometric insight is that for any algebraic quotient, the kernel of the quotient homomorphism (the ideal) is reduced to $0$, and any affine space parallel to that ideal is also reduced to a single point (but nonzero).
If you really in need of a visualization, I'd suggest taking a 3D graphing calculator like GeoGebra, and graphing $f(x, y) = x^2 - y^2 + C$, making $C$ vary, and trying to understand how reducing these surfaces to a point (for each $C$) will draw a line/curve. Though this is not at all your example, it should give you an analogy of what's happening; your example is much simpler to understand algebraically than it is to visualize geometrically.
Edit: a previous version of this answer mistakenly claimed that $\mathbb{R}[x,y]/(x^2−y, x−x^3+xy)$ was a curve, when it is, in fact, a point. This has been corrected; and @Viktor Vaughn's answer accepted as correct. The points I make on algebraic quotients still hold, though, so I have left them unchanged.
Comment: The variety corresponding to $\mathbb{R}[x,y]/(x^2-y,x-x^3+xy)$ is a point, not a curve. This is visible from the isomorphism $\mathbb{R}[x,y]/(x^2-y,x-x^3+xy) \cong \mathbb{R}$ since $\mathbb{R}$ has Krull dimension $0$.
Comment: You are right; my lack of knowledge of algebraic geometry shows. I upvoted your answer and will edit mine immediately to reflect my mistake. Thank you for correcting me !
Answer: Here's how I think about it. $\mathbb{R}[x, y]$ is the ring of all polynomial functions on $\mathbb{R}^2$ under pointwise addition and multiplication. The "$\mathbb{R}$" on the right-hand side of your isomorphism is not some abstract version of the real field. It's actually all polynomial functions whose domain is the single point $(0, 0) \in \mathbb{R}$.
Thought of in these terms, the restriction from $\mathbb{R}^2$ to $\{(0, 0)\}$ corresponds to the obvious surjective map $\mathbb{R}[x, y] \to \mathbb{R}$ given by $x \mapsto 0, y \mapsto 0$ that just picks off the constant term. This is a ring homomorphism because function arithmetic is defined pointwise, which restriction clearly respects.
As for the ideal $(x^2-y, x-x^3+xy)$, passing to the quotient $\mathbb{R}[x, y]/(x^2-y, x-x^3+xy)$ literally says we want to consider all polynomial functions on $\mathbb{R}^2$ with the additional relations that $x^2-y = 0$ and $x-x^3+xy = 0$ but no others except those implied by these. The claimed isomorphism is a concrete geometric way to think of what this abstract quotient "looks like": if it's true, it says that any two polynomials in $\mathbb{R}[x, y]$ with the same constant term can be shown to be equal if you allow yourself to write $x^2-y=0$ and $x-x^3+xy=0$ in intermediate steps, and that there is no additional "collapsing" beyond this.
To prove it, first off the two relations respect restriction to $\{(0, 0)\}$ since $0^2 - 0 = 0$ and $0-0^3+0\cdot0 = 0$, so restriction continues to give a surjective map $\mathbb{R}[x, y]/(x^2-y, x-x^3+xy) \to \mathbb{R}$. It is natural to ask if this map is injective as well. Geometrically, that's equivalent to asking: having imposed the two abstract relations above and no more, can I have two different polynomial functions which have the same value at $(0, 0)$?
Before answering that question, let's consider what would happen if $x^2-y$ and $x-x^3+xy$ were also both zero at some point $(a, b)$ different from $(0, 0)$. Then we could pick polynomials $p(x, y), q(x, y)$ such that $p(0, 0) = q(0, 0)$ yet $p(a, b) \neq q(a, b)$. Using the restriction to $\{(a, b)\}$ rather than $\{(0, 0)\}$, that would force $p \neq q$ in the quotient even though their constant terms are the same, so the map would not be injective. Hence more common zeros keep the quotient bigger. However, it's easy to see there are no common zeros here beyond $(0, 0)$, so this obstruction doesn't appear in this case.
It's inevitable at this point that we'll have to start playing with algebra. For instance, we get the same obvious surjection $\mathbb{R}[x, y]/(x^2, y^2) \to \mathbb{R}$ by restricting to $\{(0, 0)\}$, but the quotient is larger. (The map which takes the partial derivative with respect to $x$ and then evaluates at $(0, 0)$ is well defined.)
Ok, let's play. We've got $y=x^2$ and $xy=x^3-x$. If we could divide by $x$ the second would be $y=x^2-1$ and then we'd have imposed $0=-1$ which would result in the zero ring and everything would collapse completely. But we can't divide by $x$, roughly since that might mean dividing by $0$. But if we multiply $y=x^2$ by $x$ we can do almost the same thing: $xy = x^3$ and $xy = x^3-x$. Together this says $x=0$, but since $y=x^2$ we get $y=0$ too. Thus in the quotient $p(x, y) = p(0, 0) + x(\cdots) + y(\cdots) = p(0, 0)$ always, and our map is indeed injective, hence bijective, hence an isomorphism.


How to calculate skewness and kurtosis in parallel?

Question: I wanted to know is there any way to calculate skewness and kurtosis of a set as a combination of skewness and kurtosis of its subsets ?
So,
For example if my data is,
<code>X = {1,2,5,7,8,9,0,10}
A = {1,2,5}
B = {7,8,9}
C = {0,10}
</code>
Is there any way to express the skewness and kurtosis of X as a combination of skewness and kurtosis of A,B and C ?
Comment: Short answer: strictly, no since the skewness of the combined sample is not only a function of the skewness of the subsamples (similarly for kurtosis). Longer answer: yes, if you add in other information. If you have all of the lower order moments, its possible.
Answer: Two disjoint sets with $n_1$ and $n_2$ observations in them. The full set has
$$n=n_1+n_2$$

The first central moment (mean):

$$\mu=\frac{\sum_{i=1}^nx_i}{n}=\frac{n_1\mu_1+n_2\mu_2}{n}$$

The second central moment (variance) can be computed using central to non-central moment relationship:
$$\sigma^2=\frac{\sum_{i=1}^nx_i^2}{n}-\mu^2=\dots$$

Use the same approach as for the mean to compute full set's non-central moment from that of its subsets:
$$\sigma^2=\frac{(\sigma^2_1+\mu^2_1)n_1+(\sigma^2_2+\mu^2_2)n_2}{n_1+n_2}-\mu^2$$

For skewness use third non-central and central moment relationship to obtain 3rd central moment as follows:
$$\gamma=\frac{1}{n}\left(\sum_ix_i^3-3\mu\sum_ix_i^2\right)+2\mu^3$$
The same idea works for kurtosis

This Mathematica page can be helpful
Comment: Are you using $\mu^3$ to mean two different things in that last equation? Normally it would represent the cube of the mean. Did you mean to write $\mu_3$ on the left hand side? I'm also concerned about the use of $\mu,\sigma$ etc for sample quantities without clearly differentiating this from the usual convention (that Greek letters are for parameters, not sample statistics), since it seems to encourage a common cause of student confusion.
Comment: Thanks to both of you.

I think the link which I am currently trying to understand uses the same approach of finding lower order moments to achieve the same.

Can you comment on approach documented [here](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics) ? Is it the same or requires some modifications ?
Comment: The parallel algorithm formulas should work. You can apply them recursively to incorporate several such groups.
Comment: Yes that algorithm is similar in terms of using lower order moments to compute higher


Confidence intervals with gamlss package

Question: My question regards the use of the gamlss package. I am using gamlss package to fit a dataset to a logistic function. There is only one predictor, let me denote it with x and because the overall dependence is not exactly sigmoid, a better model is achieved by wrapping the predictor x in a smoother function. I chose the cubic spline smoother (cs). The response is binomial. I'll denote it with y:
y = cbind(number of successful events, total number - number of successful events).

The R code is  the following:
cs15 <- gamlss(y~cs(x, df=15), sigma.fo=~1, family=BI,  data=mydata, trace=FALSE)

I want to estimate predicted response for a set of predictors not contained in the original data set. I know this can be achieved with the function:
cs15fit = predict(cs25, newdata=data.frame(x=xnew), type="response")

However, my problem is that I also want to estimate the standard errors, which should be done by adding se.fit=T:
cs15fit=predict(cs25, newdata=data.frame(x=xnew), type="response", se.fit=T)

But the addition of se.fit = T produces the following error:

se.fit = TRUE is not supported for new data values at the moment

Anyone know how I can still find standard errors for the new values?
Comment: Is your question about how to get the code to work, or about the issues underlying getting standard errors here?
Comment: The code works. The issue is that obtaining standard errors through this package (gamlss) for this case is not possible . So if there is any work around, i.e.  how  can I find them myself.
Answer: It sounds like you want prediction intervals. The se.fit argument name reflects that it will give you standard errors extracted from the original fit, and it sounds like it does this only if you do not specify newdata -- i.e. want the prediction of the original fit. (And my suspicion is that it might be giving you standard errors of your coefficients rather than prediction intervals.)
So you want to search for 'prediction interval of GAM' rather than 'standard errors'. I found a couple of papers that way, but that's just the GAM case and GAMLSS (being more flexible) is going to be even more difficult to get right.
I'd suggest falling back to a GLM -- are you sure that your "better model" isn't overfitting and that it makes a substantial difference if it's not -- where things are more straightforward and the posting @boro141 links to is applicable. (Note that you have to do more than get the se.fit results even in that case.)
http://opensiuc.lib.siu.edu/cgi/viewcontent.cgi?article=1095&context=gs_rp
Answer: See the answer to this question: How are the standard errors computed for the fitted values from a logistic regression?
The linked answer relates to a glm. I am not sure whether using a smoothing term as you have done affects the standard error calculation, but it should give you an idea of how standard errors are computed in predict.
Comment: +1. They key here is that these "standard errors" are _prediction intervals_, not standard errors of coefficients. The description by the OP and the title of the linked posting are both misleading, but the linked posting does give the correct answer.


Finding out remainders

Question: No idea how to proceed with this question:-
$P=2008^{2007}-2008$
$Q=2008^2+2009$
The remainder when $P$ is divided by $Q$ is
Any theorem or lemma used, just tell me what it is along with the solution
This question is from a regional maths contest.This question came and I couldn't make out any possible way to solve it.
I thought of applying modulo but the values were far too large.
Comment: Did you try anything yourself? It's unlikely that someone will give you a step by step solution given that you didn't give as any information as to what did you try,where did you get stuck,where this question is coming from and such.
Comment: Synthetic division won't work (as the divisor is a quadratic), but I'm sure you can find a generalisation of it by searching it up. What else have you tried? Where did you find the question? At what level is the question aimed at? I'm sure you can add extra context on your question to help people answering.
Comment: In one sentence: show some context @sayan and put effort so people will ACTUALLY answer.
Comment: Expanding the first few terms (x^2+x+1)^1003 using the binomial theorem will show a clear pattern, from there you can $x^{2007}-1$ from the expansion.
Comment: By Maple the reminder is $4032066=2\times 3 \times 19 \times 113 \times 313$, maybe useful.
Answer: ${\rm mod}\ a^{\large 2}\!+a+1\!:\,\ 0\equiv (a^{\large 2}\!+a+1\!)(a\!-\!1)\equiv a^{\large 3}-1\ $ so $\ \color{#C00}{a^{\large 3}\equiv 1}\ $ so $\ \color{#0a0}{a^{\large 3n}}\equiv (\color{#c00}{a^{\large 3}})^{\large n}\equiv \color{#c00}1^{\large n}\equiv \color{#0a0}1$
hence $\ \color{#0a0}{a^{\large 3n}}\!-a\,\equiv\, \color{#0a0}1\!-\!a.\,$ Yours is case $\,a = 2008,\ 3n= 2007\, (\equiv 2\!+0\!+\!0\!+\!7\equiv 0\pmod{\!\!3})$
Remark $ $ More generally, as above $\ a^{\large J}\! + a^{\large K}\! \equiv a^{\large J\,{\rm mod}\,\color{#c00} 3}+ a^{\large K\,{\rm mod}\, \color{#c00}3}\,\pmod{\!a^{\large 2}\!+a+1}$
For example $\ a^{\large 2}\!+\!a\!+\!1\mid a^{\large J}\! +\! a^{\large K}\! +\! a^{\large L}\ $ if $ \ \{J,K,L\}\equiv \{2,1,0\}\pmod{\!3}$
Seee this answer for further related examples.
Answer: If you put $x=2008$ you have to divide $$\frac{x^{2007}-x}{x^2+x+1}$$
Now to make calculations easier lets divide by $x^3-1=(x-1)(x^2+x+1)$ which is easy since $x^3-1\mid x^{2007}-1$
$$\frac{x^{2007}-x}{x^3-1}=x^{2004}+x^{2001}+x^{1998}+\cdots+x^3+1+\frac{1-x}{x^3-1}$$
Multiplying by $x-1$ you get that $$\frac{x^{2007}-x}{x^2+x+1}=(x-1)(x^{2004}+\cdots+x^3+1)+\frac{1-x}{x^2+x+1}$$
Now since having a negative number as remainder is not convenient use the fact that $1-x\equiv Q-(1-x)\pmod{Q}$
Now just replace $Q$ with the actual value.
Comment: +1 if you put a link to the Remainder Theorem or give a little explanation of the Remainder Theorem. Without that, it is near impossible to find more information on the topic.

Finding out remainders


How to stop text-boxes in my custom block trailing past the block?

Question: I am creating a module with a custom block.  Even through googling, I still could not find an answer to my question "how do you theme the elements in a form?"  I think it is the fact that I don't completely understand the array elements that need to be set on each textbox.
Image of my problem: https://www.evernote.com/shard/s188/sh/3bf8cc91-5341-4c55-91ca-41e0ddbd1922/feb9698ff407e60a064f92421510059d
Comment: If you want to reduce length by CSS or make div wider, it's a purely CSS problem, not really Drupal related. Only if you want to make inputs shorter by changing their length parameter, it's actually a Drupal question. But if so, you need to write it more clearly in your question.
Answer: While creating this form in your custom module you set DIV class to form items which is textfield in your casy. All you will have to do is use #prefix & #sufix
You will start your DIV class from #prefix before #type of form items & close the DIV at #sufix.
Here is the example
$form['first_name'] = array(
  '#prefix' => '
',
  '#title' => t('First Name'),
   '#type' => 'textfield',
  '#suffix' => '
',
  '#maxlength' => 128,
  '#required' => TRUE,
);

Open the CSS file or create your own at your theme folder, but if you create your own then you will have to declare it in theme.info file.
Write CSS for the class demo-form which you have applied to the form element & resize it as your wish. If you have created your own CSS file then don't forget to clear your cache.
Comment: Turns out I was missing the "#size" array key in the $form['first_name']. Thanks for you contributions!


Entity field query pager only loads first page

Question: How do I load any page other than the first page with Entity Field Query pager?
$query = new EntityFieldQuery();

$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->pager(4)
  ->execute();

This returns the first 4 nodes. If i have 12 nodes, how do I return page 2 nodes 4-8 or page 3 nodes 8-12.
The documentation states I can only pass $limit and $element. Have I missed something? What's the point of a pager that only loads the first page.
Answer: Here are some pointers:

The query looks fine
Try adding the parameter ?page=1 to your request and you should see different items. Page 0 is the one you see by default.
You need to display the pager object while building your output, like:
$output['pager'] = array('#theme' => 'pager'); This will make the pager visible and allow users to click on back/next buttons to navigate through pages to see other items which are not on the current page.


print webpage source from HtmlAgilityPack

Question: I'm new to C# coming from a python background. I've had a hard time figuring this out. In python I can use beautifulsoup to do this:
from bs4 import BeautifulSoup
import requests
r = requests.get('http://stackoverflow.com').content
soup = BeautifulSoup(r).prettify
print soup

This gets the source content of stackoverflow.com, and prints it in to the console.
I CANNOT figure out how to do this in C#.
        var webGet = new HtmlWeb();
        var document = webGet.Load("http://stackoverflow.com");
        Console.WriteLine(document);

This does not work, it only prints the type of var document. Does anyone know how to do this? It would be much appreciated - I'm trying to learn C# by converting one of my python programs, just fyi.
Comment: When using HtmlAgilityPack, it *really* helps to know the .NET framework's built-in XmlDocument class. They have nearly the same API.
Answer: Use the OuterHtml property of the DocumentNode:
var webGet = new HtmlWeb();
var document = webGet.Load("http://stackoverflow.com");
Console.WriteLine(document.DocumentNode.OuterHtml);


Fluxxor pass flux object to the child component

Question: I want to pass flux object to a child component instead a parent.parent component is inside render function. there I dont wanna pass fluxxor instance .
I wanna something like this . Is it possible ?
<code> var Main = React.createClass({
    render: function() {
        return (
                <Application flux={flux} />

        );
    }

});
</code>
I am using Fluxxor for fluxx
Answer: With Fluxxor, if you need access to Flux from a child component, you don't need to pass it down in a prop, instead you use the FluxMixin:
<code>var FluxMixin = Fluxxor.FluxMixin(React);

var Application = React.createClass({
  mixins: [FluxMixin],
  someFunction: function() {
     var flux = this.getFlux(); // getFlux is available due to mixin
  }
  //...
};
</code>
This is all described in detail here: http://fluxxor.com/guides/quick-start.html


Unselect an Android View when selecting another one

Question: I have 4 ImageView's inside a LinearLayout. There is also a selector.xml file that sets background color red when android:state_selected="true"
What I want is to have only one view selected. I don't know how I can keep a reference to the last selected view so I can unselected it.
The code I have so far is :
<code>        ImageView beer = (ImageView)findViewById(R.id.beer_button);
    ImageView coffee = (ImageView)findViewById(R.id.coffee_button);
    ImageView food = (ImageView)findViewById(R.id.food_button);
    ImageView wifi = (ImageView)findViewById(R.id.wifi_button);

    beer.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "1");
               v.setSelected(true);
           }
    });

    coffee.setOnClickListener(new OnClickListener() {
           public void onClick(View v)     {
               Log.v("flag", "2");
               v.setSelected(true);
           }
    });

    food.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "3");
               v.setSelected(true);
           }
    });

    wifi.setOnClickListener(new OnClickListener()   {
           public void onClick(View v)     {
               Log.v("flag", "4");
               v.setSelected(true);
           }
    });
</code>
Answer: <code>water.setOnClickListener(new OnClickListener()   {
       public void onClick(View v)     {
           Log.v("flag", "0");
           ((LinearLayout)v.getParent()).dispatchSetSelected(false);
           v.setSelected(true);
       }
});
</code>
Comment: or `((ViewGroup)v.getParent()).dispatchSetSelected(false);`
Answer: You can use Radiogroup and don't worry about selected state. Or when select image deselect ones.
Use radiogroup is best way:
1. you don't duplicate code.
2. any time you can get selected item.
Comment: How I know which one to deselect?
Comment: when select keep ref to selected item. But use radiogroup is more prefer in this case.
Comment: I will change it to RadioGroup. Thank you
Answer: Besides @slientnuke's answer, you can also do something like this:
<code>// First define imageViews as global
private ImageView beer, coffee, food, wifi;

// Find them and set their click event to one
beer = (ImageView)findViewById(R.id.beer_button);
coffee = (ImageView)findViewById(R.id.coffee_button);
food = (ImageView)findViewById(R.id.food_button);
wifi = (ImageView)findViewById(R.id.wifi_button);

beer.setOnClickListener(selectionListener);
coffee.setOnClickListener(selectionListener);
food.setOnClickListener(selectionListener);
wifi.setOnClickListener(selectionListener);

// Define selectionListener
private OnClickListener selectionListener = new OnClickListener() {

    public void onClick(View v) {
        beer.setSelected(false);
        coffee.setSelected(false);
        food.setSelected(false);
        wifi.setSelected(false);

        v.setSelected(true);
    }

};
</code>


Get from certain sql range

Question: I have the following video table:
create table videos(
  title text,
  date_range text);

insert into videos(title, date_range) values
('Title1', '["2021-03-18 - 2021-03-20", "2021-03-01 - 2021-03-05", "2021-03-15"]'),
('Title2', '["2021-02-12 - 2021-02-13", "2021-02-02 - 2021-02-06","2021-02-10"]');

+--------+----------------------------------------------------------------------+
| title  |                date_range                                            |
+--------+----------------------------------------------------------------------+
| Title1 | ["2021-03-18 - 2021-03-20", "2021-03-01 - 2021-03-05", "2021-03-15"] |
| Title2 | ["2021-02-12 - 2021-02-13", "2021-02-02 - 2021-02-06","2021-02-10"]  |
+--------+----------------------------------------------------------------------+

How to get videos from 2021-03-18 - 2021-03-19?
So the result table should look like this:
+--------+----------------------------------------------------------------------+
| title  |                date_range                                            |
+--------+----------------------------------------------------------------------+
| Title1 | ["2021-03-18 - 2021-03-20", "2021-03-01 - 2021-03-05", "2021-03-15"] |
+--------+----------------------------------------------------------------------+

Here you have fiddle with this table, but with no result, because I do not know how to achieve this.
Thanks in advance!
Comment: Consider normalising your schema
Answer: A normalised schema might be somewhat as follows:
id title  date_range_start date_range_end
 1 Title1 2021-03-18       2021-03-20
 2 Title1 2021-03-01       2021-03-05
 3 Title1 2021-03-15       2021-03-15
 4 Title2 2021-02-12       2021-02-13
 5 Title2 2021-02-02       2021-02-06
 6 Title2 2021-02-10       2021-02-10

Comment: I do not want to do that, is it any way to do this without normalizing schema?
Comment: Strawberry is right here. If you want to be able to make dated queries, you'll have to normalize the way he did. You could also have a table with the titles linked to a daterange table to achieve the same. Anyway your schema is not suitable for date queries.
Comment: As I see it you have two choices: 1. Normalise your schema. 2. Don't bother with an RDBMS

Get from certain sql range


Copying image from a worksheet using openpyxl

Question: I have a Python program that creates a new excel file based on some worksheets from a few other files. The following code I have copies the worksheets perfectly, but is unable to copy the image that is present in the worksheet. How do I copy images in an Excel worksheet to another Excel workbook using Python?
path1 = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Uploaded_files/" + key
print path1
path2 = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Compiled/"  + current_acc_group + "_" + current_gl_account + ".xlsx"
print path2
path_to_key_sheet = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Uploaded_files/" + key + "_key_sheet.txt"
print "Path to key sheet file:"
print path_to_key_sheet

wb1 = xl.load_workbook(filename=path1, read_only=True, data_only=True)
ws1 = wb1.worksheets[2]
counter = 0
for sheet in wb1:
   if (str(sheet.title) == str(content_of_key_sheet_file)):
       ws1 = wb1.worksheets[counter]
       print "Sheet selected"
       print sheet.title
   counter = counter + 1

ws2 = wb2.create_sheet(ws1.title)
print "Copying from the Excel file: " + path1
for row in ws1:
   for cell in row:
       if (cell.value != None):
          ws2[cell.coordinate].value = cell.value

wb2.save(path2)

Answer: install Pillow (just pip install Pillow, not needed import in your file)
then:
from openpyxl import drawing

.
.
.
img = drawing.image.Image('yourImg.png')
yourSheet.add_image(img, 'A2')

where A2 is your cell
Comment: `Pillow` is already installed. Still the image appears blank(placeholder) in the destination worksheet.
Answer: I'd been struggling with this for a bit as most of the libraries I typically use to manipulate xlsx files seemed to not want to support this.
Fortunately, .xlsx is ooxml format.  Thus, all you need to do is unzip the .xlsx and locate the pictures in xl/media/ of the directory you extracted your workbook to.
zip = ZipFile('yourWorkbook.xlsx')
zip.extractall()

Now you can insert them back into your new spreadsheet spreadsheet
import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')


I am wondering why I cannot override jquery function onRegionOver. The WAMP index.html file is shown below

Question: I am wondering why I cannot override jquery function onRegionOver. The WAMP index.html file is shown below. Please tell me how I can use the WAMP console to debug this problem.
The jquery plugin I am trying to make work on my Windows 7 Internet Explorer IE7 browser here is http://jvectormap.owl-hollow.net/.
<!DOCTYPE html>

  <title>jVectorMap demo</title>
  <link rel="stylesheet" href="jquery-jvectormap-1.1.1.css"
type="text/css" media="screen"/>

Answer: .vectorMap() function accepts a single object with multiple parameters, while you're passing 2.
Presumably the call should look like:
    pluginContainer.vectorMap(
       {
           map: 'us_aea_en',
           onRegionOver: function(event, code){
               alert('Hello');
           }
       }
     );

References:

http://jvectormap.com/examples/world-gdp/
http://jvectormap.com/documentation/javascript-api-v1/jvm-worldmap/
Comment: I just tested your answer and it works with WAMP2.4_x86.
Comment: @Frank: it's javascript it works on a client - so it *doesn't matter* what is installed on the server.
Comment: @@zerkms;Please explain why your code is javascript  instead of jquery
Comment: ;Please explain why your code is javascript instead of jquery
Comment: @Frank: are you sure you understand what terms `javascript` and `jquery` mean? Asking it because your question doesn't make much sense.
Comment: ;I understand what the terms javascript and jquery mean. Could you please look at some vectormap code?
Comment: @@zerkmsI understand what the terms javascript and jquery mean. Could you please look at some vectormap code?
Comment: @Frank: that's what stackoverflow is for. If you have another question - just ask another question.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/44475/discussion-between-frank-and-zerkms)
Comment: @@zerkmes; I solved the problem The HTML regions USA-map and container overlap. I removed the HTML region container. Thanks for all of your help help this evening. I am going to sleep now.


Two different books are giving two different solutions.

Question: So I am solving some probability/finance books and I've gone through two similar problems that conflict in their answers.
Paul Wilmott
The first book is Paul Wilmott's Frequently Asked Questions in Quantitative Finance. This book poses the following question:

Every day a trader either makes 50% with probability 0.6 or loses 50% with probability 0.4. What is the probability the trader will be ahead at the end of a year, 260 trading days? Over what number of days does the trader have the maximum probability of making money?

Solution:

This is a nice one because it is extremely counterintuitive. At first glance it looks like you are going to make money in the long run, but this is not the case.
Let n be the number of days on which you make 50%. After $n$ days your returns, $R_n$ will be:
$$R_n = 1.5^n 0.5^{260−n}$$
So the question can be recast in terms of finding $n$ for which this expression is equal to 1.

He does some math, which you can do as well, that leads to $n=164.04$. So a trader needs to win at least 165 days to make a profit. He then says that the average profit per day is:

$1−e^{0.6 \ln1.5 + 0.4\ln0.5}$ = −3.34%

Which is mathematically wrong, but assuming he just switched the numbers and it should be:

$e^{0.6 \ln1.5 + 0.4\ln0.5} - 1$ = −3.34%

That still doesn't make sense to me. Why are the probabilities in the exponents? I don't get Wilmott's approach here.
*PS: I ignore the second question, just focused on daily average return here.

Mark Joshi
The second book is Mark Joshi's Quant Job Interview Question and Answers which poses this question:

Suppose you have a fair coin. You start off with a dollar, and if you toss an H your position doubles, if you toss a T it halves. What is the expected value of your portfolio if you toss infinitely?

Solution

Let $X$ denote a toss, then:
$$E(X) = \frac{1}{2}*2 + \frac{1}{2}\frac{1}{2} = \frac{5}{4}$$
So for $n$ tosses:
$$R_n = (\frac{5}{4})^n$$
Which tends to infinity as $n$ tends to infinity

Uhm, excuse me what? Who is right here and who is wrong? Why do they use different formula's? Using Wilmott's (second, corrected) formula for Joshi's situation I get the average return per day is:
$$ e^{0.5\ln(2) + 0.5\ln(0.5)} - 1 = 0% $$
I ran a Python simulation of this, simulating $n$ days/tosses/whatever and it seems that the above is not correct. Joshi was right, the portfolio tends to infinity. Wilmott was also right, the portfolio goes to zero when I use his parameters.
Wilmott also explicitly dismisses Joshi's approach saying:

As well as being counterintuitive, this question does give a nice insight into money management and is clearly related to the Kelly criterion. If you see a question like this it is meant to trick you if the expected profit, here 0.6 × 0.5 + 0.4 × (−0.5) = 0.1, is positive with the expected return, here −3.34%, negative.

So what is going on?
Here is the code:
import random
def traderToss(n_tries, p_win, win_ratio, loss_ratio):
    SIM = 10**5 # Number of times to run the simulation
    ret = 0.0
    for _ in range(SIM):
        curr = 1 # Starting portfolio
        for _ in range(n_tries): # number of flips/days/whatever
            if random.random() > p_win:
                curr *= win_ratio # LINE 9
            else:
                curr *= loss_ratio # LINE 11

        ret += curr # LINE 13: add portfolio value after this simulation

    print(ret/SIM) # Print average return value (E[X])

Use: traderToss(260, 0.6, 1.5, 0.5) to test Wilmott's trader scenario.
Use: traderToss(260, 0.5, 2, 0.5) to test Joshi's coin flip scenario.

Thanks to the followup comments from Robert Shore and Steve Kass below, I have figured one part of the issue. Joshi's answer assumes you play once, therefore the returns would be additive and not multiplicative. His question is vague enough, using the word "your portfolio", suggesting we place our returns back in for each consecutive toss. If this were the case, we need the geometric mean not the arithmetic mean, which is the expected value calculation he does.
This is verifiable by changing the python simulation to:
import random
def traderToss():
    SIM = 10**5 # Number of times to run the simulation
    ret = 0.0
    for _ in range(SIM):
       if random.random() > 0.5:
                curr = 2 # Our portfolio becomes 2
            else:
                curr = 0.5 # Our portfolio becomes 0.5

        ret += curr

    print(ret/SIM) # Print single day return

This yields $\approx 1.25$ as in the book.
However, if returns are multiplicative, therefore we need a different approach, which I assume is Wilmott's formula. This is where I'm stuck. Because I still don't understand the Wilmott formula. Why is the end of day portfolio on average:
$$ R_{day} = r_1^{p_1} * r_2^{p_2} * .... * r_n^{p_n} $$
Where $r_i$, $p_i$ are the portfolio multiplier, probability for each scenario $i$, and there are $n$ possible scenarios. Where does this (generalized) formula come from in probability theory? This isn't a geometric mean. Then what is it?
Comment: $\mathrm{e}^{0.6\ln 1.5+ 0.4 \ln 0.5} \approx 0.9666$ is in a sense the weighted geometric mean outcome while $0.6\times 1.5+ 0.4 \times 0.5=1.1$  the weighted arithmetic mean outcome, with the weights being the probabilities.   You might subtract $1$ from each for a measure of the gain, but if you have $n$ repeated applications, then you in fact want to raise each of these to the power of $n$ before subtracting the $1$.
Comment: Take a more extreme example: each day you you either quadruple your funds or you lose everything, with equal probability.  After $n$ days, your expected funds are $2^n$ times your original stake, and this is increasing rapidly, but the probability you have any money at all left is $\frac{1}{2^n}$ and this is falling rapidly.
Comment: They are different problems, and you ask multiple different questions about them. So it's a little hard to tell where to start with unravelling it all. But you also say that Wilmott says: profit per day is: $1−\mathrm{e}^{0.6\ln 1.5+ 0.4 \ln 0.5} = −3.34%$" and that he says: "the expected profit, here 0.6 × 0.5 + 0.4 × (−0.5) = 0.1, is positive". Does he really say both??
Comment: Your first simulation code has an issue. You are taking an AM of 10^5 simulations, while you should be taking the geometric mean.
Another way to put it is to remove the n_tries parameter, and compute single ret value for 10^5 tosses. You will get a value of 0.
Answer: The difference is that a $50$% loss and a $50$% gain (in either sequence) result in a net loss (AM-GM inequality), whereas halving and doubling (in either sequence) do not result in a net loss.  Joshi is presenting (and solving) a different problem, one in which half the time the trader's expected return is $100$%.  So there's no a priori reason to expect the same result.
Having said that, Wilmott's answer to the Joshi question is wrong.  For $n$ tosses, $R_k=2^k(\frac 12)^{n-k}=2^{2k-n}$, where $k$ is the number of times you toss heads.  Wilmott's analysis of Joshi assumes that you are starting afresh each time with a single dollar.
Wilmott's solution to his own problem is correct.  If you take ten trials, you expect a return of $1.5^6 \cdot 0.5^4 -1 = \frac{729}{1024}-1 = -\frac{295}{1024}$.  Taking the geometric mean gets you $\sqrt[10]{1.5^6 \cdot 0.5^4} -1 = 1.5^{0.6} \cdot 0.5^{0.4}-1$, which is exactly what Wilmott says (just writing it in exponential form).
Comment: If your "position doubles," you have made 100%, not 50%.
Comment: Joshi says that $50$% of the time "your position doubles."  I do agree with you that the solution given for the Joshi problem is wrong, though.  I'll edit my answer to note that.
Comment: If you find an answer useful, upvotes and acceptances are always appreciated.
Comment: Well isn't a 50% loss the same as halving? And a 50% gain the same as multiplying by 1.5?
Comment: I also am not familiar with the AM-GM inequality, so maybe this is part of the reason?
Comment: I understand, I never said that if my position doubles I've made 50%. In fact I said that a *50% gain is the same as my position multiplying by 1.5x*, following that logic, *a 100% gain is the same as multiplying my position by 2x*. The Wilmott formula uses the multiplicative factor not the gain. The Joshi formula uses the gain. Both reach different results. Which is correct?
Comment: I'm getting somewhere thanks to these comments, I'm using my Python sim to validate my hypotheses. Will update my question momentarily as well
Comment: This answer has helped a lot, but it still doesn't answer my main problem: the Wilmott formula for average daily return. I've updated my question to reflect my progress
Comment: I've again revised my answer.
Answer: They're computing two entirely different things. Wilmott is computing the minimum number of days out of $260$ on which you must make a profit in order to come out ahead; Joshi is computing the expected value of your portfolio. Applying Joshi's calculation to Wilmott's setting, we get an expected value after $260$ days of
$$(0.6\cdot1.5+0.4\cdot0.5)^{260}=1.1^{260}\approx 57,833,669,934\;.$$
Wilmott's calculation does not take the probabilities of the two outcomes into account: it would yield the same result whether you made a $50\%$ profit with probability $0.99$ or with probability $0.01$. In the former case, however, you are almost certain to make a net profit, while in the latter you are almost certain to lose virtually everything. No matter what the probabilities are, you need to make a profit on at least $165$ days in order to come out ahead for the year; your likelihood of actually doing so, however, changes greatly with the probabilities.
In the original problem you might find it odd that the expected number of days on which you make a profit is $60\%$ of $260$, or $156$ days, and you lose money if you make a profit on exactly $156$ days, yet your overall expected value is enormous. This is because once you reach the break-even point, your expected final value grows explosively as the number of profitable days (out of $260$) increases, and these huge profits more than compensate for the more likely losses.
If you want to know how likely it is that you'll make a profit, you want Wilmott's calculation; you can then plug the figure of $165$ days into a binomial distribution calculator and find that the probability of making a profit on at least $165$ days is only about $0.14$. The fact that the expected profit — expected in the mathematical sense, that is — is considerable would probably not be very comforting, since it results from the fact that relatively unlikely outcomes produce huge profits.
Answer: The crucial thing is that Wilmott asks about the chance of making a profit, regardless of how large the profit or loss is.  Joshi is asking about expected value of the portfolio.  Those are very different questions.  If I pay $1$ to bet on something and win $10$ with probability $\frac 15$ but can only play once, Wilmott says I should not.  I lose $80\%$ of the time.  Joshi says I should play, because my expected return is $2$.  They are asking different questions and getting different answers.
Answer: Joshi's problem is a much easier problem and he is correct. Wilmott's problem is a little bit more subtle, and I think he is misleading about what he is computing. The main point is that returns are not additive, so the trap is to compute expectation of the return on a given day and then "add it up" to conclude that you are expected to win overall. It's counterintuitive that this does not work.
So Wilmott is correct when he says that the expected profit on day 1 is
$$
0.6 \times (1.5 - 1) + 0.4 \times (0.5 - 1) = 0.1.
$$
If we write $X$ for the return on day 1, then:
$$
\mathbb{E}(1+X) = 0.6 \times 1.5 + 0.4 \times 0.5 = 1.1.
$$
I think Wilmott's language is misleading for the newcomer (which is annoying as he's supposed to be famous for teaching basic quant principles to newcomers). By "average profit per day" in the sentence you quote he seems to be referring to something like "expected daily rate of profit". To shed a bit more light on what he means, suppose you want to compute the expected return after $n$ days: To do this, let $X_1,\dots, X_n$ be i.i.d. random variables where $X_k$ is defined as the return on day $k$. These are not additive: The return after $n$ days is given by the random variable $R_n = (1+X_1)(1+X_2)\cdots (1+X_n)$. But log-returns are additive:
$$
\log R_n = \sum_{i=1}^n \log (1+X_i),
$$
so that by linearity of expectation (and i.i.d. assumption) we can compute the expectation of the log-return now as:
$$
\mathbb{E}(\log R_n) = n \mathbb{E}(\log (1+X)) = n\Bigl(0.6 \log 1.5 + 0.4 \log 0.5\Bigr).
$$
So you can see that what matters in the long run for the expected log-return is the whether the expression in the brackets on the right-hand side is bigger than zero or not.

Wilmott seems to use the value of
$$
e^{\mathbb{E}(\log R_1)} - 1 = e^{(0.6 \log 1.5 + 0.4 \log 0.5)} - 1
$$
to make the same point I am making above. But since we've taken an expectation, we can't pull the $\mathbb{E}$ through a logarithm or exponential to "convert" easily back to $\mathbb{E}(R)$. I don't know... this might be one of this quant things that is used as a measure of rate of return but isn't the same as $\mathbb{E}(R)$.
Comment: I can't agree with you more about Wilmott. His book is horrible. Really good questions, but really half-assed solutions. *Back to the question*, in your $\log R_n$ formula you never bring up the probability factor. How does the weighted geometric factor into this formula?
Comment: I'm not sure what you mean about the probability factor, the equation for $\log R_n$ is arrived at by just manipulating the random variables themselves.Then when you take the expectation, you need to use the probability distribution of $X$.
Comment: Oh my bad, I misread. Yeah now I get it. Not sure which answer to accept as this question has been answered real well by everyone. I think your answer helped the most though since it addressed the author's logic, so I'll be accepting this
Answer: The answer by Brian M. Scott shows the main effect at work: In the Wilmot scenario, the expected value after 260 trading days is enourmous, but the probability of it actually being higher than the starting value is small. That's not at odds with each other, it'
s how the expected value works when you can in theory make enourmous gains.
Wilmot does make an error however when he calculates the average profit per day, where you don't understand the formula. I'll try to show how he got there, and where the error was:
If you run his scenrio for $k$ days, then the number of "good days" (where you make $50\%$) is a random variable $G_k$, and the number of "bad days" (where you loose $50\%$) is also a random variable $B_k$. Both variables follow a binomial distribution (Bin), where $G_k \sim \text{Bin}(k,0.6)$ and $B_k \sim \text{Bin}(k,0.4)$.
Now, Wilmot correctly uses the fact that the value of the return after $k$ days is
$$R=1.5^{G_k}0.5^{B_k}.$$
You can find this in his formula
$$R_n=1.5^n0.5^{260-n},$$
because this talks about the $260$ trading days scenario (so $k=260$) and he defined $n$ to be the number of good days you have (so $n=G_{260}$). This shows that that first terms ($1.5$ to the power of something) are the same in both formulas. Also, we have $G_k+B_k=k$ (each day is either good or bad), so $B_{260}=260-G_{260}=260-n$, which shows that the secnd terms ($0.5$ to the power of something) are also the same.
Again, up to here everything is correct. We have $R=1.5^{G_k}0.5^{B_k}$, so $R$ is also a random variable. Now we know what the expected values of $G_k$ and $B_k$ are, for a binomial distribution that's easy to calculate:
$$E(G_k)=0.6k,\, E(B_k)=0.4k.$$
The error, I assume, that they did was to use the above correct formulas and incorrectly conclude that
$$E(R)\overset{\color{red}{\text{wrong}}}{=}1.5^{E(G_k)}0.5^{E(B_k)}=1.5^{0.6k}0.5^{0.4k}=\left(1.5^{0.6}\times0.5^{0.4}\right)^k.$$
The last part of the formula seems to show that the return changes by a factor of
$$1.5^{0.6}\times0.5^{0.4} = e^{0.6\ln(1.5)+0.4\ln(0.5)} \approx 0.9666 $$
each day, which corresponds to the $3.34\%$ loss per day they calculated.
The error here is that if $f(x)$ is any non-linear function, then if $X$ is a random variable then generally
$$E(f(X)) \neq f (E(X))$$
Comment: Right, it is $1.1^{260}$ times the original amount.
Comment: So if I were tasked to find the expected value of this scenario after 260 days, **Joshi**'s answer is the correct one?


Show that if $E\subset\mathbb{R}$ is a measurable set, so $f:E\rightarrow \mathbb{R}$ is a measurable function.

Question:
If $E\subset \mathbb{R}$ is a set Lebesgue Measurable and $f:E \rightarrow \mathbb{R}$ a monotone function, show that $f$ is measurable.

I'm trying for hours with no progress.
Comment: I do not remember where I first found this fact, but it is stated on the wikipedia article on monotone functions:

http://en.wikipedia.org/wiki/Monotonic_function

The theorem itself is found here:

http://en.wikipedia.org/wiki/Froda's_theorem
Comment: And what have you done so far?
Comment: What form does $f^{-1}((c,\infty))$ have, for $c\in \mathbb{R}$?
Comment: @5xum
Apply the definition of a function mensurable (in $\mathbb{R}$):
$f$ is mensurable if $f^{-1}(I)$ is mensurable SET for any interval $I$
Comment: OK. Try examining what $f^{-1}(I)$ can be, using the fact that $f$ can only have a countable set of points where it is not continous.
Comment: @5xum because we know this about monotone functions? This is a result that I don't know, can you detail or give me a hint?
Comment: @5xum can you detail for me this afirmation about monotone functions or give a reference to I read? This like usefull!!
Answer: Every monotone function is even Borel measurable, and in particular Lebesgue measurable. To see this, first let $f$ be an increasing function on $\mathbb{R}$. Let $a \in \mathbb{R}$.
Define $F_a=\{ x\ \in \mathbb{R} : f(x) \leq a \}$, and we want to show $F_a$ is a measurable set, from which we will conclude f is measurable.
Now if $F_a=\varnothing $ then obviously $F_a$ is measurable, and we are done.
So assume $F_a\not =\varnothing $, and let $x_0=\sup F_a$, There are 3 different options:
1)if $x_0=\infty$, then $F_a=\mathbb{R}$ is measurable.
2)if $x_0 \in F_a$ then $F_a=(-\infty,x_0]$.
3) if $x_0 \not \in F_a$ then $F_a=(-\infty,x_0)$.
and in any case $F_a$ is a borel set, and so f is measurable.
Now for f decreasing you may note that $-f$ is an increasing function, so it is measurable, and therefore $f$ is measurable too.