What are modes in the real world?

Question: For months, I have been trying to understand modes.
Even though I have memorized all the names, what notes they start from and so on, I do not understand their meaning in the real world of music making.
Let's say I have the C Major scale: C D E F G A B.
I always like to have the freedom of picking notes as I want.
For example in the background the C major chord is playing, and I am playing a melody on my guitar. One phrase starts from C; 3 seconds later, another phrase I play starts from F.
Does it really mean that each phrase is based on a different mode?
This is insanely confusing for me. Does it really matter what note I start from and which note ends a phrase? It is the same bunch of notes played in a different order.
It would mean that every song in the world is using all the modes all the time...
Some people say it is all about emphasizing some particular notes. Does it mean I have to use D much more than the other notes to underline the Dorian sound in a C major melody?
Why in the world do we complicate the theory so much?
We could say that if you start your C major scale from D, it would sound  a particular way. All these mode names are literally ruining my music world right now.
Modes do not let me sleep at night for a long time.
Please help me understand, thank you :)
Comment: Mode is much more about the note a melody *ends* on than about the note it *starts* on.
Comment: Do you understand the difference between A minor and C major? It's the same as that, but with all the other letters.
Comment: In my opinion you can make music without ever thinking or talking about modes. After all, they are simply the result of combining keys, chords and scales, and not an additional entity. If you don't find them helpful, ignore them. (Although it can be useful to know the terminology, so you can understand what other people are talking about and translate it to your own way of thinking about music.)
Comment: In my first answer - I've deleted it as I've realized that I didn't read correct or misunderstood your concern - I tried to explain the modes, but you obviously know what they are. Now I'm going to  rewrite my answer.
Comment: "...3 seconds later, another phrase I play starts from F note." What chord is in the accompaniment, is it still a C chord?
Comment: "what notes they start from and so on" What do you mean "notes they start from"? Modes are just the interval pattern as you ascend/descend the scale. Any mode can start from any note. You haven't lived until you've improvised in G# Phrygian.
Answer: Try this - play D E F G A and back again. Then play a C major chord (CEG). Does the chord sound like it would fit under the tune? Possibly not. But you've used 5 of the 7 notes that constitute the C major key! What you heard first was a snippet of tune that probably came from D Dorian - a mode from the parent key C. But it sounded minor, and C is major! It worked because it centred around the sound of D Dorian - with the D note being a particular 'home' point.
We don't make the theory any more complicated than it is - in fact, we try very hard to simplify it - but sometimes that's difficult. We understood that given the 7 notes of a major scale, any one of those notes could be 'home', making the relationship it has with the others different for each mode (with the exception of Locrian...). We tried to explain it away - maybe not too successfully for you (and many others!) but that's all we can do.
Does a piece change modes al the time? Probably not - although many tunes wander from major to natural (or other) relative minor, and we aren't even aware that it's happening unless we listen with a very critical ear. It's not that important, unless we're analysing the piece.
Knowing modes exist is often enough. I know polar bears exist, but have nothing to do with them! Keep on making your own music, and one day, you may find you've come up with something a little bluesy, and realise it's more at home finishing on G, even though you've only played C scale notes. When you do, youve been using G Mixolydian. Not that that matters much - it's a technical term, and that doesn't bother lots of players!
For now, just keep modes information safely somewhere, as it maybe won't be much use yet. But keep playing, and keep an open mind as to keys and what they do, and how using notes from them in different ways can affect which direction their tunes can take.
Comment: The notes D E F G A don't give the characteristic dorian sound even if we have established D as the root tone. This is because they don't contain the sixth interval so we can't pinpoint whether it is in D dorian or D aeolian. Since aeolian (= ordinary minor) is more common than dorian, many people will perceive such a melody correspondingly.
Comment: Technically, C major doesn't nevessarily point to D Dorian; D natural minor also contains a C major chord. B♮ is the note that would support D Dorian.
Answer:
For example in the background there is playing C major chord and I am
  playing melody on my guitar. One phrase starts from C note, 3 seconds
  later, another phrase I play starts from F note.
Does it really mean that each phrase is based on different mode?

No. Modes are not a classification system for melody snippets based on starting or ending notes. Forget about starting and ending notes, they have nothing to do with modes. Modes are about harmony around a tonic. Harmony is about things that sound or could sound simultaneously and how the simultaneously played combinations would make you feel, not about sequential start/stop positions. Forget about starting notes, forget about melody lines, forget about scale runs, forget about note sequences, modes are about harmony. Those things can be said to affect modal feeling only if they affect the overall harmonic feeling. Do they? Ask yourself. Looking at starting and ending notes will not tell you how you feel about harmony.
Where is the tonic? If you don't know what tonic means, you don't know what modes mean. Tonic is not a starting note or ending note in a note sequence you could look at. The tonic doesn't even have to be played or sounded at all, yet it can exist in the listener's mind. It's the expected home note, home base, origin, place of reference, zero point, center of the world.
Modes are harmonic feelings created through specific intervals relative to a tonic i.e. home note. Mood would often be a better term. For some reason modes are explained in a misleading way, by talking about starting or ending notes for a scale. Even though the starting note thing is a technically justifiable way for constructing mode definitions and it's not incorrect for that purpose, it won't help you get familiar with modes like you can get familiar with, say, what foods taste like.
If you're familiar with chords and how they're used in songs, and how they move the harmonic feeling around, it might be much easier to understand modes via chords. For example, if in regular A minor tonality you have Am and Dm chords, in A dorian mode, you have Am and D major. And if you know how D minor and D major differ, you'll know that the difference between regular A minor and A dorian is that in A dorian there's an F# note instead of F natural.
So, what are modes in the real world? If you encounter part in a song that's clearly "in A" so that A is the home note, and it's clearly A minor, but instead of F and Dm there's D major, then chances are the feeling or mood at that point is A dorian. Or the other way around, if you have a song that's in Am and you feel that the home note is A, if on top of that you play a D major chord, you have created an A dorian feeling.
Another example. Take "Happy Birthday" in F major, and play it to the end. When the song is in the final note and the final F major chord is playing, if on top of that F chord you play a G major chord, then you have created an F lydian feeling.
I'll copy-paste examples of lydian and dorian modes from this answer https://music.stackexchange.com/a/88298/51766

Here is a small etude in A lydian, (constructed with guitar chords), with the open A string as a pedal tone, fixing the sense of home note to A. The scale has the same notes as the E major scale, but the tonic is not E.

If we take the same notes, but move the pedal tone from A down to F#, we get an F# dorian sound. The pedal tone moves the tonic i.e. home note. (the sense of tonic is somewhat subjective, but I'd claim that most people will say the pedal tone here is the tonic)

Did I say it clearly? Forget about starting notes. Modes are about harmony. If the played notes, whatever notes they are and in whatever order and start/stop anything, if they don't affect your harmonic feeling, they don't affect the mode. It is possible to use solo instruments so that single-note lines affect harmonic perception very effectively, but even then you consider the overall harmonic feeling, you don't mechanically look at starting and ending notes.
Comment: I understood modes much better when I started thinking about them harmonically rather than just melodically
Comment: D major can also exist in A minor - F# is present in A melodic minor, so the piece doesn't *necessarily* have to automatically be in A Dorian. And what's 'regular Am'?
Comment: @Tim Playing a D major chord in an Am context gives me a dorian feeling. And I said there's an F# in A dorian, not that every time there's an F# it has to be dorian and cannot be anything else. Melodic minor is a scale for melodies, and if you play E - F# - G# - A, behind the F# there can be e.g. B7, which has a D# note, which does _not_ belong to A melodic minor. Modes are much better seen as harmonic, not melodic concepts, IMO. The way modes are usually explained is confusing, as if the people couldn't tell the difference between melody and harmony. :)
Answer: No, merely starting a phrase on a different note doesn't put you into a different mode.   Consistently ENDING phrases on a different note or chord might though!   You're in D Dorian rather than C Ionian (equivalent to C major) when D becomes established as the home note.
Here's an example.
Comment: That is not terribly helpful, accurate as it may be. Can you explain a bit more or annotate?
Comment: You don't understand. Which is something I see a lot with people who are knowledgable in something. Try to place yourself into someone's shoes who knows very little about music theory. They see your post where you talk about D dorian and C Ionian. And then you post an example of music with a repetition of A notes, then some other ones, a repetition of G notes, etc. You don't see how that might be confusing? And how with just a little bit of extra explanation your post and example would be better? And the fact that 6 people have upvoted the "that is not terribly helpful" comment?
Comment: If it's _demonstrably_ rooted on D, _demonstrate_ it's rooted on D. I.e. how do you deduce that?
Comment: It uses the notes of C major but is demonstrably rooted on D.  What more do you want me to say about it?
Comment: Except the second part of the first line, the song seems to be mainly written between A (the fifth of D) and D (the er... fundamental of D). That would mean the base note for the song would be D. Were it in mode of C (the usual), you would need a signature with 2 sharps (F# and C#). The signature is empty and there is no accidental (including on F and C) so the scale used seems to have only unaltered notes ABCDEFG based on D, so the scale used is D E F G A B C D, which puts the song in mode of D. I'm not a music expert, so I may be wrong.
Comment: @LaurencePayne Well yes, you wouldn't want your answer to be TOO helpful, right? Look man, what can I say? You answered, it could be improved, you don't want to. Because... I don't know why actually, a fragile ego perhaps? Ok, then. Leave it as it is and revel in its perfection.
Comment: Play it. Sing it. Listen to it. If you can't hear where the root is, you're probably not equipped to discuss musical matters!
Comment: "Consistently ENDING phrases on a different note" is the gist of my explanation.   And yes, I think it pointless to think about questions of music theory until you're fluent at musical rudiments.
Comment: Feel free to expand on it in your own answer.  My ego won't be offended!
Answer: I agree with Michael Curtis and other answers that bring out the importance of harmonization and the harmonic character of "modes" as used in contemporary musical styles.
But I also would add one thing that's missing in the answers here so far, which is that modes are not scales, at least not as traditionally understood.  A mode is more than a scale, and a mode (at least historically, and as still used to talk about older repertoires and various repertoires of traditional music around the world) is traditionally a melodic phenomenon.
Briefly, modes as understood melodically had to do with the usage of various notes in the scale, along with the patterns and stereotypical melodic gestures they would create (including cadences).  There's often an emphasis placed on the idea of a "home note," so that what makes C Ionian different from E Phrygian is the fact that the "home note" changes from C to E.
But that's only a small part of actual modal practice around the world.  Gregorian chants in "Phrygian mode" were originally classified by several things, including the most common notes other than the "home note" and the typical melodic cadential gestures.  (That's part of the reason for the distinction between Phrygian and Hypophrygian modes, which both have a finalis ("home note") on E.  Yes, the difference between Phrygian and Hypophrygian is often discussed as a difference in register or range of the melody, but it was more complicated than that -- these two modes have different characteristic melodic gestures.)
It may seem that this is far from modern practice, but we still have this embedded in the traditional "minor mode" as practiced in more classically-oriented genres.  The "minor mode" is NOT the Aeolian scale.  In fact, more confusion has been created by trying to discuss "natural minor" and "harmonic minor" and "melodic minor" scales, when really they're just trying to get at what it means to be in the minor mode, which is more than a scale.
To be in the minor mode isn't just to have a home note (say, C) with a minor third typically used above it.  It's not just a key signature either.  To be in the minor mode also means having a leading tone that tends to move up (B-C).  It also means having a flattened sixth scale degree that tends to move down (Ab-G).  It also means that when one wants to create a smooth stepwise melody, one uses gestures like G-A-B-C, but C-Bb-Ab-G.  It means that G is often felt as a secondary point of stability - a possible arrival point at middle cadences.  It means that final cadences usually happen on C, and the strongest melodic ones move D-C or B-C.  And there are many other tendencies that constitute the classical "minor mode," and its melodic characteristics.  It's more than a scale -- it's a mode.
Similarly, to be "in E Phrygian," at least from a traditional melodic standpoint, often includes cadences that emphasize the descending leading tone motion F-E.  In chant, often an emphasis on the notes A or C was common (as a sort of equivalent to the "dominant," then called the "tenor" note).  There were stereotypical melodic cadences and other stereotypical melodic gestures (turns around certain notes of the scale, patterns that might fall or rise to a certain note, etc.).
Such principles are alive and well today in "modes" as used around the world.  Again, modes can be seen as more than a scale, but one can go even further.  Is an Indian rag a "mode"?  I'd say it's probably more than a mode, as the gestures in particular raga are often even more strictly determined than in most modes.  Go further in terms of making music that's more melodically determined, and you end up with things like Irish tune families, patterns of melodies that sound very similar with whole phrases alike (used both in standard tunes and in improvisations around them).
Broadly speaking, "modes in the real world" when one steps outside of pop/jazz/contemporary theory often refers to a really fascinating concept of melody that's somewhat more determined than a scale, but less determined than a specific tune.  One might also even think of it a bit like the kinds of stereotypical riffs and gestures one might learn in jazz to improvise in a particular style over a particular standard progression.
I mention all of this because the concept of "modes as a primarily harmonic phenomenon" is somewhat recent.  The more traditional meaning of "mode" as a collection of melodic characteristics for playing in a particular style (as well as a particular scale) is still alive though, if increasingly relegated to the usage of ethnomusicologists and historians.
Answer: Modes are more useful for harmonic purposes than they are for melodic purposes.
Lets imagine you're playing a II-V-I chord progression in C Major (Ionian). Your chords are going to be Dm-G-C.
If you play the same progression in D Dorian (same notes), you're going to be playing Em-Am-Dm. This will still have the same general cadence, but will have a very different feel, so some composers find it interesting to write modal harmony.
Furthermore, when writing or improvising a melody it can be useful to put the chord tones of the current chord on the down beats, so playing in the correct mode and knowing where the passing tones fall within the key can be useful.
Ultimately modes are just a way of re-conceptualizing a scale, and while understanding them can be essential for playing in a specific style, such as hard bop, if they aren't an interesting tool they may not be worth diving too deeply into.
Comment: You have to be very careful with modal cadences. Em-Am-Dm doesn't sound dorian to me. Say I have establish D as the root note by playing Dm for a while. The change to Em now does sound very dorian but changing to Am afterwards makes me perceive Am as the new root chord.
Answer: For some reason, many guitar teachers use modes as a short-hand for playing the same scale in different positions rather than because the student is really ready to understand modal theory. If this is what you've encountered, then just concentrate on learning the patterns of the major & minor scales across the fretboard.
If/when you are actually interested in forms of music that truly use modes—such as modal jazz—then proceed. (In that case, other answers are probably more useful than any I could give.)
Answer:
What are modes in the real world?

A common description of the modes is they are the permutations of the major scale. Ex. the C major scale is CDEFGABCDE..., Dorian modes uses that sequence of tones, but starting on D as DEFGABCDEF..., Phrydian starts on E as EFGABCDEFG....
Historically that is partly true. In old Church music the system used the gamut of letters ABCDEFGA... and the various modes started on the different letters. But what is left out of simplistic descriptions of the modes is that in the old Church music chromatic alterations would occasionally be used for harmonic reasons like avoiding a tritone or forming a proper cadence. So, in D Dorian mode a sharp would be added to make C# for a cadence. Or a flat might be added to make Bb to avoid a tritone with F.
A more modern approach can view modes as flavoring or shading of major and minor scales. Those flavorings and shadings are made by raising or lowering tones. For example, if we lower the second degree of a minor scale (Aeolian mode) it produces the Phrygian mode. One way this can occur is with a Neapolitan chord. You could say the Neapolitan chord brings in a Phrygian flavor to a minor scale. Another common example is Mixolydian in rock and blues music. The progression I V bVII IV is an example where a major key gets a Mixolydian flavoring.
So, in the real world, using modes isn't simply playing a scale on a different starting note. Using modes changes the tonal - the harmonic - palette of music.
Answer: It is like you say! Don't worry about modes.
They are very rarely in usual Popmusic, in Jazz they may be more often used but you can handle the modes like I do in Baroque music:
When I play music e.g. by Fisher or Bach in a Dorian or Phrygian mode I don't mind the mode at all.  It is possible to read them by adding (imaging) another flat or sharp that it will fit with a related (nearest) minor or major key.
So don't bother. I agree that the role of the modes is rather a theoretical problem than they would be of practical interest.
Answer: Confusion concerning the modes mostly comes from ignoring the root note.
The root note is the note which creates a feeling of being at home, fully released tension, etc. and it is the most important thing in music. Instead of looking at the modes as "starting" from different notes of the major scale, I  suggest to look at the different modes using the same root note for all of them.
The familiar characteristic sounds of ordinary major and minor tonality are determined by which intervals in relation to the root note occur. Using C as root note, here are the two scales:
Scale of C-major:  C - D  - E  - F  - G  - A  - B  - C
Scale of C-minor:  C - D  - Eb - F  - G  - Ab - Bb - C

As you can see, the differences between the two are the third, the sixth and the seventh interval. The modes simply are different collections of intervals which lead to different characteristic sounds. These sounds can be roughly sorted from bright to dark. You can hear them in the following example songs:
lydian:           "Flying in a Blue Dream" by Joe Satriani
ionian (= major)  "Blowing in the Wind" by Bob Dylan
mixolydian:       "Norwegian Wood" by The Beatles
dorian:           "Scarborough Fair"
aeolian (= minor) "Lady in Black" by Uriah Heep
phrygian:         "Wherever I May Roam" by Metallica
locrian:          the first part of "Army of Me" by Björk

Again using C as root nore, the notes which are used in the modes are the following:
C-lydian:              C - D  - E  - F# - G  - A  - B  - C
C-ionian (= C-major):  C - D  - E  - F  - G  - A  - B  - C
C-mixolydian:          C - D  - E  - F  - G  - A  - Bb - C
C-dorian:              C - D  - Eb - F  - G  - A  - Bb - C
C-aeolian (= C-minor): C - D  - Eb - F  - G  - Ab - Bb - C
C-phyrigian:           C - Db - Eb - F  - G  - Ab - Bb - C
C-locrian:             C - Db - Eb - F  - Gb - Ab - Bb - C

The first three of these modes contain the C major chord C-E-G, the second three contain the C minor chord C-Eb-G and the last one contains the diminished chord C-Eb-Gb. If you want to play in a certain mode, simply chose the chord quality which is associated with the mode for the accompaniment and use the notes of the mode from the table for the melody.
For example, if you use a C major chord for the accompaniment you perceive C as the root note. If you play the notes of the ordinary major scale in the melody you get an ordinary major sound. You can now pass to a lydian sound by raising the 4th interval by a semitone (playing F# instead of F) or to a mixolydian sound by lowering the seventh interval by a semitone (playing Bb instead of B).
Let me again emphasize the importance of the root note: C-ionian (= C-major), D-dorian, E-phrygian, F-lydian, G-mixolydian, A-aeolian (= A-minor) and B-locrian all have the exactly same notes. If you play these notes over a F-major chord, the root note is F and you get the bright lydian sound. If you play these notes over an E-minor chord, the root note is E and you get the dark phrygian sound. So which of these sounds you get depends on the root note of the musical situation.
This corresponds exactly to the situation in ordinary major (= ionian) and minor (= aeolian). The scales of C-major and A-minor contain the same notes. Whether you get a major or a minor sound depends on the musical situation, i.e. on whether C or A is perceived as the root note.
Answer: Modes are simply different ways to construct scales; instead of making alterations to key signatures with which you're already familiar, changes that make no rhyme or reason other than, "You do it this way to get this sound," you're taking key signatures you already know (because they're the key signatures for all 15 major scales) and applying them to different progressions.
A saxophone professor once explained the concept this way to me, and it made modes make perfect sense: there are seven modes, and each has a different, distinct tonal quality. Some are major, some are minor, and there's even a couple that are diminished. These tonal qualities can be ranked from brightest to darkest thus:
Lydian
Ionian
Mixo-Lydian
Dorian
Aolian
Phrygian
Locrian
...with Lydian being the brightest mode and Locrian being the darkest.
I remember that order using the first letters as a word: LIMDAPL. I admit it's not the best mnemonic device, but it works for me.
The wonderful thing about modes is that you only need to know three things in order to be able to construct any mode at a moment's notice: all 15 key signatures (which you should know anyways), how to construct a circle of fifths (which you should know anyways), and the meaning of the non-word LIMDAPL (which I've explained above).
Let's say you want to construct a mode that started on D. To do so, you'd draw a circle, write "I" at 12:00, "L" at 1:00, "M" at 11:00, and continue writing the first letters of each of the modes at each of the subsequent hour marks, with the second "L" landing on 7:00, like so (forgive the crudeness):

Since you want to construct a mode starting on D, place D at the 12:00 spot, like so:

From here, say you want to make D Lydian: you'd move to that spot on the circle and adjust the key signature by the appropriate amount. In this case, you've moved one spot to the right, so you'd add one sharp to what D Ionian is. If you have three sharps, they are F#, C#, and G#, in that order. Strangely enough, those three sharps are also how you make A major/A Ionian. Therefore, D Lydian is a D scale in the key of A:
D E F# G# A B C# (D)
It works every single time. Say you want E Phyrygian: put E at 12:00, then move around the circle until you get to "P". Count how many steps you've made, then adjust the key signature: from Ionian to Phrygian is
I > M > D > A > P
That's four steps around the circle. To make the adjustment, subtract 4 sharps from E's key signature. E major only has four, so E Phrygian has no sharps and no flats; in other words, E Phrygian is an E scale with the C major key signature.
What about G Dorian? Ionian to Dorian is
I > M > D = two steps.
G only has one sharp, so you have to both subtract a sharp and add a flat. In other words:
G Ionian is a G scale in the key of G major
G Mixo-Lydian is a G scale in the key of C major
G Dorian is a G scale in the key of F major
Once you're able to do this on the fly, modes become a cinch.
As others have noted, modes are used often in jazz: when you're trying to solo, you're thinking about the chords as they change through the piece, which can be daunting. Using modes is a way to simplify the process.
Hopefully this was helpful. Just remember to add sharps/subtract flats and add flats/subtract sharps in the right order (order of flats is BEADGCF, order of sharps is FCGDAEB).
Let me know if I need to clarify something. Good luck!
Answer: I disagree with others on here that say you shouldn't worry about modes. Modes are extremely important and you'd be really limiting yourself musically if you don't understand them. They're all over the place in various songs and they're very distinct.
But you're thinking about this in a wrong way. It's not about the notes. It's about the intervals and how they are ordered.
For example the ordering of intervals in major is:W W H W W W H
Order of dorian is: W H W W W H W
And each other mode has its unique ordering.
Melodically this means that each mode has a distinct sound. You don't get the "do re mi fa so la ti do" sound that major makes. You get a completely different sound for example here's solfege for natural minor/aeolian. Harmonically, because of these intervals each mode has a different ordering of minor and major chords. You were partially right saying you'd emphasize the root note in the mode, that's for melody, and that's the tonal center. Harmonically you'd emphasize the first chord of the mode and this chord serves as the "home" or resolution chord. every other chord serves a harmonic function that relates back to this first chord.
You'll notice, because of these intervals, that some modes (Aeolian, Dorian, Phrygian, Locrian) are considered minor modes. And the others (Ionian, Lydian, Mixolydian) are considered the major modes. This is due to their first chord being either minor or major.
The more you practice modes, the more you'll start to recognize them. Scarborough Fair for example is in Dorian. Pieces that sound middle eastern are usually Phrygian, for example white rabbit by jefferson airplane. or more often a tweak to phrygian called phrygian dominant (which is actually a mode from the harmonic minor scale). Spacey sounding modes like Lydian is used in ET theme and simpsons. Each mode has its own character and purpose and people use them to get a certain sound/feeling. Especially look into movie theme music, they make use of different modes in order to get a certain feel.
The more versed you are with modes the more you'll hear them in songs. you can't mimic a mode. It has its own character. For example Scarborough Fair a song in Dorian, cannot be played in minor or major. Its distinct ordering of intervals is what makes it sound Dorian.
Lastly, don't think of modes as "modes". Just think of it as an entirely different scale, with its own character and set of chords.

What are modes in the real world?


Different predictions on multiple run of the same algorithm scikit neural network

Question: Since a MLP can implement any function. I have the following code, using which I am trying to implement the AND function. But what I find that on running the program multiple times, I end up getting different predicted values. Why is this happening ? Also how does one determine which type of activation function has to be provided at different layers ?
from sknn.mlp import Regressor,Layer,Classifier
import numpy as np
X_train = np.array([[0,0],[0,1],[1,0],[1,1]])
y_train = np.array([0,0,0,1])
nn = Classifier(layers=[Layer("Softmax", units=2)],learning_rate=0.001,n_iter=25)
nn.fit(X_train, y_train)
X_example = np.array([[0,0],[0,1],[1,0],[1,1]])
y_example = nn.predict(X_example)
print (y_example)

Answer: For reproducibility you should set the random seed for your code.
import random
random.seed(2016)

Random seed accepts any hashable object. You will most commonly see a number in there. It is an optional argument, if you don't pass it it will use the system time as seed.
Another way to achieve reproducible results is to set the random_state=int as argument of Classifier in your code.
You can use any number of hidden layers. In order to set the function for each layer, define the first argument of Layer(). That's 'Softmax' in your code.
It is recommended to use a pipeline for the construction of your network. You should also normalize your data. In the below code you can see an example:
from sknn.mlp import Classifier, Layer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler

pipeline = Pipeline([
        ('min/max scaler', MinMaxScaler(feature_range=(0.0, 1.0))), #normalization
        ('neural network', Classifier(layers=[Layer("Softmax")], n_iter=25))])

Then you call
pipeline.fit(X_train, y_train)


Como alterar o background de um JDateChooser?

Question: Eu tenho um JDateChooser e gostaria de alterar o background quando ele ganhasse focu, porém eu não estou conseguindo.
Eu tentei fazer de algumas maneiras:
dataChooser.getDateEditor().getUiComponent().setBackground(new Color(0, 0, 0));

ou
dataChooser.setBackground(new Color(0, 0, 0));

e isso eu coloquei dentro do evento de focusGained
import com.toedter.calendar.JDateChooser;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

public class BackGr extends JFrame {

    JDateChooser data = new JDateChooser();
    JPanel painel = new JPanel();

    public BackGr() {
        setSize(300, 150);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        painel.add(data);

        data.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                data.getDateEditor().getUiComponent().setBackground(new Color(0, 0, 0));
                //data.setBackground(new Color(0, 0, 0));
            }

            @Override
            public void focusLost(FocusEvent e) {
            }
        });

        add(painel);
    }

    public static void main(String[] args) {
        BackGr bg = new BackGr();
        bg.setVisible(true);
    }
}

Comment: Por favor, adicione um **[mcve]** do seu código para que seja possivel testar e ver o problema em execução.
Comment: @Articuno coloquei lá, desculpa !
Comment: O que significa esse `focu` que você destacou?
Comment: focu , no sentido de entrar com o cursor no campo, acho que escrevi errado.
Comment: A aplicação já abre com esse campo em foco?
Comment: nesse caso esta, porém eu testei sem iniciar direto com o focu, e o resultado é o mesmo.
Answer: Se o objetivo é alterar diretamente o campo de texto, você precisa adicionar o evento no editor do JDateChooser. Para isso, recupere o componente editor através do método getDateEditor():
JTextFieldDateEditor dateChooserEditor = ((JTextFieldDateEditor)data.getDateEditor());

Depois, adicione o evento de "foco" direto nele:
dateChooserEditor.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {

        dateChooserEditor.setBackground(new Color(0, 0, 0));
    }

    @Override
    public void focusLost(FocusEvent e) {

    }
});

Porém, dessa forma vai alterar permanentemente o background do componente. Se o objetivo é somente mudar quando estiver focado nele, uma alternativa é armazenar a cor padrão do background e restaure-a quando perder o foco:
dateChooserEditor.addFocusListener(new FocusListener() {

    Color defaultBG = dateChooserEditor.getBackground();

    @Override
    public void focusGained(FocusEvent e) {

        dateChooserEditor.setBackground(Color.CYAN);
    }

    @Override
    public void focusLost(FocusEvent e) {

        dateChooserEditor.setBackground(defaultBG);
    }
});

Veja um exemplo da alteração acima em pratica:


How to find the coefficient of this Fourier sine series?

Question: From $$1=\sum_{k\geq 1} a_k \sin((k\pi+\frac{\pi}{2})x),$$
I want to find $a_k.$
My unsuccessful approach is first multiplying both side by $\cos((k\pi+\frac{\pi}{2})x)$. That is,
$$\cos((k\pi+\frac{\pi}{2})x)=\frac{1}{2}\sum_{k\geq 1}(\sin \pi x)a_k.$$
Can anyone give me a trick to find $a_k$? Thanks in advance.
Comment: Notice that $\sin(k\pi+\frac{\pi}{2})=\cos(k\pi)$.  Then, you're simply finding the Fourier cosine series of the function $f(x)=1$ (which should be fairly straightforward using the definition).
Answer: Hint: The functions $ {\cos(k\pi x)}_{k=0}^{\infty} $ are orthogonal on the interval $[-1,1]$, that means
$$  \int_{-1}^{1}\cos(k\pi x) \cos(m \pi x) dx = \begin{cases} 0 &: k\ne m \\ 2 &: k=m=0\\ 1 &: k=m \ne 0 \end{cases}\, .$$


java.lang.NoSuchMethodError: javax.ws.rs.core.MultivaluedMap.addAll(Ljava/lang/Object;[Ljava/lang/Object;)

Question: I was trying to test the "loading time" of the page by using the method "eyes.testResponseTime(driver, appName, testName, action, deadline, timeout, viewportSize);" in the following script and I got the above mentioned error. The method is from the "Applitools"(used for Visual Validation). Please help me on this and give me a solution how to use this method effectively and please give me a simple working code. Thanks in advance...
Code:
import java.net.URI;
import java.net.URISyntaxException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.applitools.eyes.Eyes;
import com.applitools.eyes.StdoutLogHandler;

public class LoadTime {

    public static void main(String[] args)  {

        Eyes eyes =null;
        WebDriver driver =null;
        try {
        driver = new FirefoxDriver();

        eyes = new Eyes(new URI("https://applitools.com"));

        eyes.setApiKey("Type_Applitools_Key_Here");

        eyes.setLogHandler(new StdoutLogHandler(true));

        // Load the applitools login page.
        driver.get("https://applitools.com/login/");

        // Enter the username and password. But don't click on "Login" just yet.
        driver.findElement(By.id("user_login")).sendKeys("Enter User Name");

        driver.findElement(By.id("user_pass")).sendKeys("Enter Password");
        Thread.sleep(4000);

            try {
                eyes.testResponseTime(driver, "Applitools Website", "Login performance test 1",
                        // We want time to be measured from when we click on the
                        // "Login" button.
                        new Eyes.WebDriverAction() {
                            public void drive(WebDriver driver) {
                                driver.findElement(By.id("wp-submit")).click();
                            }
                        }, 20,new RectangleSize(1024, 600));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } finally {
            eyes.abortIfNotClosed();
            driver.quit();
        }
    }
}

Error occurs in the Method:
    eyes.testResponseTime() Please refer the code above.
Pom.xml:
<project

xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

 <modelVersion>4.0.0</modelVersion>
    <groupId> T_TestSuite</groupId>
    <artifactId>T_TestSuite</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name></name>
    <description>AutomateT</description>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.7</jdk.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                    <compilerArgument></compilerArgument>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.14</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                    <systemPropertyVariables>
                        <buildnumber>${build.number}</buildnumber>
                        <jobname>${job.name}</jobname>
                    </systemPropertyVariables>
                    <properties>
                        <property>
                            <name>usedefaultlisteners</name>
                            <value>false</value>
                        </property>
                        <property>
                            <name>listener</name>
                            <value>org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter,com.automateon.TestProgressListener</value>
                        </property>
                    </properties>
                    <reportsDirectory>${project.basedir}/target/</reportsDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <build.number>${BUILD_NUMBER}</build.number>
                <job.name>${JOB_NAME}</job.name>
            </properties>
        </profile>
    </profiles>
    <dependencies>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.uncommons</groupId>
            <artifactId>reportng</artifactId>
            <version>1.1.2</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.testng</groupId>
                    <artifactId>testng</artifactId>

                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.8</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.52.0</version>
        </dependency>
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>LATEST</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp</groupId>
            <artifactId>okhttp</artifactId>
            <version>2.7.5</version>
        </dependency>
        <dependency>

            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.3</version>
            <type>jar</type>
            <classifier>jdk15</classifier>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp</groupId>
            <artifactId>okhttp</artifactId>
            <version>2.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.19</version>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.7.2</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
            <type>jar</type>
            <scope>compile</scope>
            <optional>false</optional>
        </dependency>

        <dependency>
            <groupId>RealTimeReports</groupId>
            <artifactId>RealTimeReports</artifactId>
            <version>1.0</version>
            <classifier>jar-with-dependencies</classifier>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/RealTimeReports.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>com.applitools</groupId>
            <artifactId>eyes-selenium-java</artifactId>
            <version>2.32</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec</groupId>
            <artifactId>jboss-javaee-6.0</artifactId>
            <version>1.0.0.Final</version>
            <type>pom</type>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
            <scope>provided</scope>

        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.22.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>2.22.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>
</project>

Console Log:
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
2016-05-03T16:12:17Z Eyes: openBase():Agent = eyes.selenium.java/2.31
2016-05-03T16:12:17Z Eyes: openBase():openBase('AppTest', 'Login Test', 'null')
2016-05-03T16:12:17Z Eyes: openBase():Eyes server URL is 'https://applitools.com'
2016-05-03T16:12:17Z Eyes: openBase():Timeout = '300000'
2016-05-03T16:12:17Z Eyes: openBase():matchTimeout = '2'
2016-05-03T16:12:17Z Eyes: openBase():Default match settings = 'Match level: STRICT, Exact match settings: null'
2016-05-03T16:12:17Z Eyes: openBase():FailureReports = 'ON_CLOSE'
2016-05-03T16:12:17Z Eyes: <init>():Driver session is 7XXXXXXXXXXXXXXXXXXXXX2
2016-05-03T16:12:17Z Eyes: testResponseTimeBase():testResponseTimeBase(regionProvider, 10, 30, 5000)
2016-05-03T16:12:17Z Eyes: testResponseTimeBase():No running session, calling start session..
2016-05-03T16:12:17Z Eyes: startSession():startSession()
2016-05-03T16:12:17Z Eyes: getDefaultContentViewportSize():getDefaultContentViewportSize()
2016-05-03T16:12:17Z Eyes: <init>():Frame chain copy constructor (size 0)
2016-05-03T16:12:17Z Eyes: <init>():Done!
2016-05-03T16:12:17Z Eyes: getDefaultContentViewportSize():Extracting viewport size...
2016-05-03T16:12:17Z Eyes: extractViewportSize():extractViewportSize()
2016-05-03T16:12:17Z Eyes: executeScript():Execute script...
2016-05-03T16:12:17Z Eyes: executeScript():Done!
2016-05-03T16:12:17Z Eyes: getDefaultContentViewportSize():Done! Viewport size: 1010x452
2016-05-03T16:12:17Z Eyes: startSession():No batch set
2016-05-03T16:12:17Z Eyes: getUserAgent():user agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
2016-05-03T16:12:17Z Eyes: getAppEnvironment():No OS set, checking for mobile OS...
2016-05-03T16:12:17Z Eyes: getAppEnvironment():No mobile OS detected.
2016-05-03T16:12:17Z Eyes: getAppEnvironment():Done!
2016-05-03T16:12:17Z Eyes: startSession():Application environment is [os = ? hostingApp = ? displaySize = 1010x452]
2016-05-03T16:12:17Z Eyes: startSession():Starting server session...
2016-05-03T16:12:17Z Eyes: abortIfNotClosed():Closed
Exception in thread "main" java.lang.NoSuchMethodError: javax.ws.rs.core.MultivaluedMap.addAll(Ljava/lang/Object;[Ljava/lang/Object;)V
    at org.glassfish.jersey.client.ClientRequest.accept(ClientRequest.java:336)
    at org.glassfish.jersey.client.JerseyWebTarget.request(JerseyWebTarget.java:221)
    at org.glassfish.jersey.client.JerseyWebTarget.request(JerseyWebTarget.java:59)
    at com.applitools.eyes.Jersey2xServerConnector.startSession(Jersey2xServerConnector.java:145)
    at com.applitools.eyes.EyesBase.startSession(EyesBase.java:1348)
    at com.applitools.eyes.EyesBase.testResponseTimeBase(EyesBase.java:1017)
    at com.applitools.eyes.Eyes.testResponseTime(Eyes.java:452)
    at com.applitools.eyes.Eyes.testResponseTime(Eyes.java:532)
    at com.TL.Test.TDB.LoadTime.main(LoadTime.java:49)

References Used:
1. http://support.applitools.com/customer/en/portal/articles/2167207-testing-your-page-s-loading-time?t=372225
2. https://eyes.applitools.com/app/tutorial.html

Answer: Solution:
I got the output and its working fine. Just created a new project on a new workspace and added the following maven dependency;
POM:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>VisualValidation</groupId>
      <artifactId>VisualValidation</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5</version>
            <configuration>
              <source>1.3</source>
              <target>1.2</target>
            </configuration>
          </plugin>
        </plugins>
      </build>

  <dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.52.0</version>
    </dependency>

    <dependency>
        <groupId>com.applitools</groupId>
        <artifactId>eyes-common-java</artifactId>
        <version>1.0</version>
    </dependency>

    <dependency>
        <groupId>com.applitools</groupId>
        <artifactId>eyes-sdk-java</artifactId>
        <version>2.24</version>
    </dependency>

    <dependency>
        <groupId>com.applitools</groupId>
        <artifactId>eyes-selenium-java</artifactId>
        <version>2.28</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.18.1</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.8</version>
    </dependency>

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.8</version>
    </dependency>

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
    </dependency>

  </dependencies>
</project>

Answer: I was facing same issue, i was able resolve it
Solution:
Eyes is using Jersey2.x by default. If you are using Jersey1.x, please do as follow:
1. Exclude eyes-connectivity-java3-jersey2x from Eyes-selenium dependency
2. Add dependency for eyes-connectivity-java3-jersey1x
Note that the version number of eyes connectivity should be the same as Eyes-selenium.


Configuring RHEL 6.6 repositories

Question: I've been given a RHEL 6.6 system which seems poorly configured - there is no subscription-manager tool available and network access has been restricted upstream.
I was able to obtain outbound HTTPS connectivity but no FTP (don't ask).
How do I configure the rhel-source.repo file so that it can pull packages from a HTTPS mirror instead of ftp?
At the moment baseurl points at:
baseurl=ftp://ftp.redhat.com/pub/redhat/linux/enterprise/$releasever/en/os/SRPMS/

Ideally I'd like to point to https://?.redhat.com/...? but I can't find a list of repositories around.
Answer: It might have been subscribed with the old style rhn_register. Or it might not have been subscribed at all, in which case yum won't work. In either case, if you need source RPMs for RHEL 6 you can log in to your Red Hat account and download them manually in addition to FTP.
Note that RHN is going away and you need to migrate the system to Subscription Management.

Configuring RHEL 6.6 repositories


Access denied: 'view published content' permission

Question: When I look into admin/people/permissions: 'View published content' is checked for anonymous users.
Yet the following code:
<code>function test_menu() {
  $items['test'] = array(
    'title' => 'Test',
    'access arguments' => 'view published content',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
</code>
returns 'Accessed denied' when I navigate to /test as an anonymous user. I know I can do:
<code>'access callback' => TRUE,
</code>
but the other code seems a lot neater. I've experienced this issue a few times before.
Thanks.
Answer: A quick look at node_permissions makes me think you should be using 'access content' as your argument, not view published content', as the latter is the proper machine name for the permission.


How to create generic AggregateService in Autofac

Question: You can do something like this:
Registration:
builder.RegisterAggregateService(typeof(IGenericAggregateService<>));

Constructor definition:
public Repository(IGenericAggregateService<TEntity> aggregateService)

but autofac can't resolve aggregateService parameter.
Is there any workaround?
Comment: What are you trying to accomplish?
Comment: @KevinR. I'm trying to resolve generic type using AggregateService
Answer: As far as I know, this is not possible. There is a workaround though. It involves a little bit of extra effort.

Create the generic aggregate service interface the same way you would create a normal aggregate service.
Create a generic aggregate service implementation with a constructor requesting all underlying services and set the properties with their provided values.
Register the generic aggregate service using the open generics registration concept.
Answer: It is now possible as of v6.1.0. Just use the overload:
builder.RegisterAggregateService(typeof(IGenericAggregateService<>));

And it will be registered as generic!


Decompile Class that have resource file

Question: I've been decompiled an aplication exe to learn about how they handle command. But I do not know exactly what type of the following file.because the file is inherit from superclass that inherit from system.windows.forms.component but also this file have resource (ExploreCommand.Resx) file in reflector.
[DesignerCategory("Accurate Command Binders"), ToolboxItem(true), DesignTimeVisible(true)]
internal class ExplorerCommands : CommandBinder
{
    // Fields
    private static readonly ResourceManager resources = new ResourceManager(typeof(ExplorerCommands));

    // Methods
    protected ExplorerCommands()
    {
    }

    public ExplorerCommands(Control control) : base(control)
    {
    }

    // Properties
    [Browsable(false)]
    public Command AboutAccurate    {
        get
        {
            return base.GetCommandForCaller("AboutAccurate ", "CitraKarya.Bisnis.Akunting.UI.Explorer.AboutAccurate ", "");
        }
    }

On every form that using this class, they declarated like this :
this.reportCommands = new CitraKarya.Akunitng.UI.ReportCommands(this);
but I dont know how command class created. They have have syntax diferent with resource class. Can anybody help me?
What does it mean? And how implemented this case?
Ough..and this the base class for exploreCommand :
CODE:
[DesignerCategory(""), DesignTimeVisible(false), Designer(typeof(CommandBinderDesigner), typeof(IDesigner)), ProvideProperty("Command", typeof(object)), TypeConverter(typeof(CommandBinderTypeConverter)), ToolboxItem(false)]
public abstract class CommandBinder : Component
{
              // Methods
    protected CommandBinder()
    {
        this.commands = new Dictionary<object, Command>();
        this.InitializeComponent();
    }

    protected CommandBinder(Control parentControl)
    {
        this.commands = new Dictionary<object, Command>();
        this.parentControl = parentControl;
        IComponent component = parentControl;
        if ((component.Site != null) && (component.Site.Container != null))
        {
            component.Site.Container.Add(this);
        }
        this.InitializeComponent();
    }

 protected Command GetCommandForCaller(string propertyName, string id, string category)
    {
        CommandManager commandManager = CommandManager;
        Command command = null;
        if (commandManager != null)
        {
            command = commandManager.Commands[id];
        }
        if (command == null)
        {
            command = CreateCommand(propertyName, id, category);
            if (commandManager != null)
            {
                commandManager.Commands.Add(command);
                return command;
            }
            CommandsToBeAdded.Add(command);
        }
        return command;
    }

}

Answer: Example of resources are strings(text), images, icons etc that one will use in the application. Instead of distributing them as different files, one can embed them into the assembly (exe/dll) and refer from there. In .NET, resource manager is a helper class to refer to these resources. Again many times, resources are associated with particular type (such as form) and known as local resources. In .NET, local resources are categorized by the type they are associated with - essentially, the resource name would have the associated type name prefix. The resource manager would taken type as an argument and then you can refer to related resources by a simple name/key (that is unique within type name). In your case, you can use reflector to see all resources associated with ExplorerCommands type - they will be categorized under particular resx (or will have name such as <Name space>.ExplorerCommands.<resource name>)
As such, resources have typically nothing to do with code logic - they just indicate some constant text or image that app needs to use.

I dont know how command class created.

From code, it appears that classes derived from CommandBinder exposes property for commands - for example, ExplorerCommands has AboutAccurate property. The property getter is in turn calling CommandBinder.GetCommandForCaller that appears to be factory method for Commands. It is looking up in the manager for pre-existing commad and if not it is invoking CreateCommand method to create the command. I believe that resources would not have any relation as far command creation goes
Comment: Thanks Vinay. I think You give me completed explanation. I can see that ExploreCommand.Resx are exist in dll. But also there are ExploreCommand.cls in the same name space.But how do I make ExploreCommand.resx while he was in the name space that is equal to ExploreCommand.cls.

Decompile Class that have resource file


Sarod rhythmic techniques (Hindustani classical music)

Question: I've been listening to some sarod recently, and what struck me is how much more rhythmic even the alaap of sarod performances tends to be than vocal or other instrumental performances. This seems to be because of certain stylistic conventions -- sarod players seem to strum certain base (fundamental? not wise in the music-theoretic ways) notes almost simultaneously with the melodic lines, which yields not only to a very virtuosic effect, but also much more rhythmically focused music (even without, say, a tabla). See, for example, Ustad Amjad Ali Khan's Raga Bageshwari (specifically see 8:00 or 17:00-24:00) or Ustad Ali Akbar Khan's Manjh Khamaj.
I was wondering if there's a name for this technique, and more importantly whether this is simply the usual method of playing sarod or whether this is a style unique to a specific gharana, or to khayal, etc.
Comment: Do you mean something like these? http://www.youtube.com/watch?v=S4owuvTF6TM and http://www.youtube.com/watch?v=Om6HDUKBbzE#t=1m42s
Comment: Could you point out specific time spans (e.g. a specific movement) in your linked examples that are good examples of what you are referring to?
Comment: Sure, sorry about that: in Ustad Amjad Ali Khan's piece, see 8:00 or 17:00-24:00 or so.
Answer: What you're referring to (17:00-24:00)is the Jhala section of the alap (improvisation). The fundamental strings you can hear are called the Chikari, which are strummed to create a syncopated effect, and allowing the sarodist to accompany himself rhythmically. It can be thought of as approximating a percussion instrument such as the pakhawaj.
I'm not sure if playing the chikari is thought of as a technique, as it can be used anywhere to fill in a rest or pause. The busier Jhala isn't really a technique either as much as a stage in the evolution of the improv.
It is not particular to any gharana. They may use the chikari as similarly or differently as the regular strings.


$y_1=\max ∣ ∣z−ω∣−∣z−ω^2||$, where $|z|=2$ and $y_2 =\max ∣ ∣z−ω∣−∣z−ω^2∣∣$, where $|z|=\frac12$ and $ω$ and $ω^2$ are complex cube roots of unity

Question:
If $y_1=\max ∣ ∣z−ω∣−∣z−ω^2||$, where $|z|=2$ and $y_2 =\max ∣ ∣z−ω∣−∣z−ω^2∣∣$, where $|z|=\frac12$ and $ω$ and $ω^2$  are complex cube roots of unity, then

A) $y_1=\sqrt3$ ; $y_2=\sqrt3$
B) $y_1\lt\sqrt3$ ; $y_2=\sqrt3$
C) $y_1=\sqrt3$ ; $y_2\lt\sqrt3$
D) $y_1\gt3$ ; $y_2\lt3$

Using $||a|-|b||\le|a-b|$,
$∣ ∣z−ω∣−∣z−ω^2||\le|w^2-w|$
So, $y_1=y_2=\sqrt3$. So, I pick option A). But the answer given is C).
Looks like it has something to do with $|z|$ but not able to make the connection.
Comment: Isn't that option A) ?
Comment: @ChargeShivers, sorry. I have made an edit. Thanks for pointing out.
Answer: The application of reverse triangle inequality is correct. The problem comes when considering whether the upper bound can actually be attained. The reverse triangle inequality states that
$$ ||a| - |b|| \leq |a-b| \, \forall a,b \in \mathbb{C},$$ with equality when $ a = rb$ for some $r \in \mathbb{R} ^ {+}.$ (note the $+$).
In this case, equality holds when $z - \omega = r (z-\omega^2)$ for some $ r \in\mathbb{R}^{+}$, which geometrically means that $z, \omega, \omega^2$ are collinear, but with $\omega, \omega^2$ on the same side of $z$.
Since $\omega, \omega^2$ lie on the unit circle, in the $|z|=2$ case we can clearly reach equality. However when $|z|=\frac{1}{2}$, if $z, \omega, \omega^2$ are collinear, then $z$ necessarily lies between $\omega, \omega^2$ (just draw a circle of radius 1 and a circle of radius $\frac{1}{2}$ to convince yourself.)
Thus equality cannot be attained in this case, so the maximum value $y_2$ must be $<\sqrt{3}$.

(When $|z| = 2$, we attain maximum at $G$ and $H$. We can never attain maximum when $|z| = \frac{1}{2}$ since the blue dot is always "between" $\omega$ and $\omega^2$.)
Comment: That's a beautiful answer, thankyou.
Answer: The triangle inequality in the form of
$\;||z-\omega|-|z-\omega^2||\le|\omega-\omega^2|,\;$
or
$$\left|\left|z+\dfrac{1-i\sqrt3}2\right|-\left|z+\dfrac{1+i\sqrt3}2\right|\right|\le\sqrt3,$$
becomes the equality if $\;z=\dfrac{-1\pm i\sqrt{15}}2,\;|z|=2.\;$
Thus, $\;\mathbf{y_1 = \sqrt3.}\;$
If $\;|z|=\frac12,\;$ then $\;|z-\omega|,|z-\omega^2|\in[\frac12,\frac32].\;$
Thus, $\;\mathbf{y_2<\sqrt3.}\;$
Therefore, the answer is C).
Appendium.
Assuming of $\;|z|=2,\;z=u+iv\;$ leads to the systems
\begin{cases}
(2u+1)^2+4v^2+3-\sqrt{(2u+1)^2+(2v-\sqrt3)^2}\sqrt{(2u+1)^2+(2v+\sqrt3)^2}=6\\[4pt]
u^2+v^2=4,
\end{cases}
\begin{cases}
4u+14 = \sqrt{4u+20-4v\sqrt3}\sqrt{4u+20+4v\sqrt3}\\[4pt]
u^2+v^2=4,
\end{cases}
\begin{cases}
(2u+10)^2-(2u+7)^2 = 12v^2\\[4pt]
u^2+v^2=4,
\end{cases}
\begin{cases}
4u+17=4(4-u^2)\\[4pt]
u^2+v^2=4,
\end{cases}
with $\;z=\dfrac{-1\pm i\sqrt{15}}2,\;|z|=2.\;$
Comment: Thankyou for the answer. How did you get $\;z=\dfrac{-1\pm i\sqrt{15}}2\;$?
Comment: @aarbee Thank you for the comment. Elaborated.


Codility performance difference: array vs hash

Question: I made a test in codility: https://codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ and I noticed a performance difference between two different solutions:
1 - List solution:
def solution(list)
  unmatched_elements = []
  list.each{ |el|
    if unmatched_elements.include? el
      unmatched_elements.delete el
    else
      unmatched_elements.push el
    end
  }
  unmatched_elements[0]
end

2 - Hash Solution
def solution(a)
  unmatch = {}

  a.each do |e|
    if unmatch[e].nil?
      unmatch[e] = 1
    else
      unmatch.delete e
    end
  end
  unmatch.keys.first
end

The first one gave me 25% performance score with some timeouts. The second one gave me 100% performance score. Why is that? I tought pushing to a Hash would result in O(n) space complexity like a List, but it seems it's not, why?
Answer: It's not about space complexity, it's about time complexity. Specifically, looking up an element in an array (include?) is a N time operation since it needs to check each element until there's a match. Hash lookup [] is constant time.
This answer explains why Hash has O(1) search time: https://stackoverflow.com/a/4363602/1034681
Comment: @Jirico: it doesn't make sense to talk about "O(N) expected worst-case time complexity" without specifying a) what you mean by "N" and b) what you mean by "time". In general, when talking about algorithmic complexity, you always need to specify a machine model (which tells you which operations are allowed) and a cost model (which tells you how costly each of the allowed operations is). You also need to specify what assumptions you can make on your data, and lastly, you need to specify how you define "input size". For example: in a Turing Machine, copying a list takes O(n²) steps, not O(n). …
Comment: In the standard Random-Access-Machine model (the most widely used since it is the one closest to how modern mainstream general purpose computers work), comparison-based sorting takes O(n log n) comparisons. But in a machine model without random access, where you are only allowed to swap adjacent elements, comparison-based sorting takes O(n²) comparisons. OTOH, if you can assume a certain kind of structure on your items, then you can sort in O(n) time (e.g. radix sort, counting sort) without using comparisons. In your specific case, you need to iterate over every element of `list` and in …
Comment: … every iteration of the loop, you need to iterate twice over every element of `unmatched_elements` (once for `include?` and again for `delete?`). `unmatched_elements` can grow and shrink, so the analysis is non-obvious, but the worst-case is if the array looks like this: `[1, 2, 3, 4, 5, 6, 7, …, 1000000, 1234567890, 1000000, 999999, 999998, …]`, so it can grow to `list.size / 2` in the worst case. That means, your complexity is O(list.size * 2*unmatched_elements.size) which is O(list.size²)!
Comment: In the test conditions it says: "expected worst-case time complexity is O(N); expected worst-case space complexity is O(1);". That's why I tought the space was the problem. Since the test returned timeouts in array case it means array search can be worst than O(N) ?
Comment: unfortunately i don't know.


Excel automation: Range.Find

Question: I want to implement this method in my c# program. But I am having trouble filling in the appropriate parameters in a line like
long FirstRow = myWorksheet.Cells.Find(
  What:="*",
  After:=Range("IV65536"),
  LookIn:=xlValues,
  LookAt:= xlPart,
  SearchOrder:=xlByRows,
  SearchDirection:=xlNext).Row

Here is the documentation for the Range.Find method.
Range Find(
    [In] object What,
    [In, Optional] object After,
    [In, Optional] object LookIn,
    [In, Optional] object LookAt,
    [In, Optional] object SearchOrder,
    [In, Optional] XlSearchDirection SearchDirection,
    [In, Optional] object MatchCase,
    [In, Optional] object MatchByte,
    [In, Optional] object SearchFormat
);

So basically I don't know how to make the appropriate parameter objects.
Update
            Excel.Range range;
        object What = "*";
        object After = xlWorkSheet.get_Range("A1", "IV65536");
        object LookIn = "xlValues";
        object LookAt = "xlPart";
        object SearchOrder = "xlByRows";
        Excel.XlSearchDirection SearchDirection = Excel.XlSearchDirection.xlNext;
        object MatchCase = System.Reflection.Missing.Value;
        object MatchByte = System.Reflection.Missing.Value;
        object SearchFormat = System.Reflection.Missing.Value;

        range = xlWorkSheet.Cells.Find(
            What,
            After,
            LookIn,
            LookAt,
            SearchOrder,
            SearchDirection,
            MatchCase,
            MatchByte,
            SearchFormat
            );

Gives a "COMException was unhandled: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
Update #2
Here is the method so far. The only thing missing is to set and return the range.
    public void RealUsedRange()
    {
        int FirstRow = xlWorkSheet.Cells.Find(
            "*",
            xlWorkSheet.get_Range("IV65536", misValue),
            Excel.XlFindLookIn.xlValues,
            Excel.XlLookAt.xlPart,
            Excel.XlSearchOrder.xlByRows,
            Excel.XlSearchDirection.xlNext,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value
            ).Row;

        int FirstColumn = xlWorkSheet.Cells.Find(
            "*",
            xlWorkSheet.get_Range("IV65536", misValue),
            Excel.XlFindLookIn.xlValues,
            Excel.XlLookAt.xlPart,
            Excel.XlSearchOrder.xlByColumns,
            Excel.XlSearchDirection.xlNext,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value
            ).Column;

        int LastRow = xlWorkSheet.Cells.Find(
            "*",
            xlWorkSheet.get_Range("IV65536", misValue),
            Excel.XlFindLookIn.xlValues,
            Excel.XlLookAt.xlPart,
            Excel.XlSearchOrder.xlByRows,
            Excel.XlSearchDirection.xlPrevious,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value
            ).Row;

        int LastColumn = xlWorkSheet.Cells.Find(
            "*",
            xlWorkSheet.get_Range("IV65536", misValue),
            Excel.XlFindLookIn.xlValues,
            Excel.XlLookAt.xlPart,
            Excel.XlSearchOrder.xlByColumns,
            Excel.XlSearchDirection.xlPrevious,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value,
            System.Reflection.Missing.Value
            ).Column;
    }

Comment: Are you using Framework 4.0? Which kind of error do you have using your syntax?
Comment: I am using the Framework 3.5. And I am aware of [dynamic type system](http://www.devx.com/dotnet/Article/42590) in 4.0 if that is what you are referring to. Currently I don't get any errors because I don't know the complete line yet to execute. For those parameters not in use, there should of course be a System.Reflection.Missing.Value object.
Answer: Not tested but this gives you the general idea:
long firstRow = myWorkSheet.Cells.Find(
    "*", /* What */
    Range("IV65536"), /* After */
    Excel.XlFindLookIn.xlValues, /* LookIn */
    Excel.XlLookAt.xlPart, /* LookAt */
    Excel.XlSearchOrder.xlByRows, /* SearchOrder */
    Excel.XlSearchDirection.xlNext, /* SearchDirection */
    Type.Missing, /* MatchCase */
    Type.Missing, /* MatchByte */
    Type.Missing /* SearchFormat */
    ).Row;

Since you can't use the optional argument syntax of VB.NET without C# v4, you need to supply all the arguments in order.  Supplying null might work for missing args but I'm pretty sure Type.Missing is the right filler.  Other than that it's just calling it like you would expect.
Here are some complete C# examples:

How to: Search for Text in Worksheet Ranges
Comment: Thank you. I might be a step closer, but I'm still having the problem of not knowing how to set the parameters correctly. Any help is appreciated. I have updated my first post with the new code.
Comment: I've ported those parameters over and added a link with all the gory details.
Comment: Thank you. That was the hint I needed:-)
Answer: Your next problem are the LookIn, LookAt and SearchOrder parameters. They shouldn't be a string, rather they are similar to the SearchDirection parameter:
object What = "*";
object After = xlWorkSheet.get_Range("A1", "IV65536");
object LookIn = Excel.XlFindLookIn.xlValues;
object LookAt = Excel.XlLookAt.xlPart;
object SearchOrder = Excel.XlSearchOrder.xlByRows;
Excel.XlSearchDirection SearchDirection = Excel.XlSearchDirection.xlNext;
object MatchCase = System.Reflection.Missing.Value;
object MatchByte = System.Reflection.Missing.Value;
object SearchFormat = System.Reflection.Missing.Value;

range = xlWorkSheet.Cells.Find(
    What,
    After,
    LookIn,
    LookAt,
    SearchOrder,
    SearchDirection,
    MatchCase,
    MatchByte,
    SearchFormat
);

Excel automation: Range.Find


about set of real sequence with meter sup ...

Question: Let
$$ X=\{ \{x_n \}_{n=1} ^{ \infty } \mid {x_n  } \to 0\ \} $$
where ${x_n  }$ is a  real sequence  and put the metric $ d(x_n ,y_n)= \sup  _{n \in \Bbb {N}} |x_n -y_n|$ on $X$.
Let $ E=\{ \{x_n \}_{n=1} ^{ \infty } \mid {x_n  } \in X, \forall n \in \Bbb {N} \ , x_{n} \geq 0 \} $  now  which of following options is true?

$E$ is not connected.
$E ^\circ = \emptyset $  .($E ^\circ $ is interior points of E)
$E ^\prime \neq E $  .($E  ^\prime $ is limit points of E)
$E$ is not closed.

I think that "2" is true because for every $a\in E , r>0 $ we have $B_r(a) \nsubseteq E$ because if we let $a= (a_1 ,a_2 ,a_3 ,...)$  there exists at least one $ t <0 , |a_1 -t| < r$ , $b= (t ,a_2 ,a_3 ,...) \in B_r(a) $ . note that  $B_r(a)= \{ x \in X | d(x,a)< r  \}$ .
Answer: Your claim that for every $a\in X $ and $r>0$ there exists a $t<0$ such that $|a_1 -t|<r$ is not true. For example, take $a_n=\frac{1}{n}$ and $r=\frac{1}{2}$. This clearly does not allow any such $t$ as you have described.
This, however, is pretty close to the right solution. Take $a\in E$ and $r>0$. Then since $\lim a_n =0$, we have that for some $N$, $a_N <\frac{r}{3}$. Let $a_t\in X$ be such that $(a_t)_n=a_n$ for $n\neq N$, and $(a_t)_N = -\frac{r}{3}$. From here the result follows. Good intuition.
1 is not true since for any two points in our space $a,b \in E$, we may construct a continuous path between them by $f(t)= ta + (1-t)b$ with component wise addition and multiplication.
3 is false since $E$ is connected and hence has no isolated points, and is closed because 4 is true.
4 is false since for any $a\in X\setminus E$, there exists at least one $a_n<0$. Hence we may let $r=|\frac{a_n}{2}|$, and then it follows that $B_r(a)\subseteq X\setminus E$.
Comment: thank's. why another options is false?
Comment: Oh sorry I thought it was multiple choice, one minute.
Comment: @amirbahadory fixed
Comment: @Noah you mean 3 and 4 are false. The question is framed in terms of negations.
Answer: Here are some hints and ideas.
No. 2 is true, 3 and 4 are false.
2:
This is because if $x_{n} \to 0$, then it becomes smaller than any fixed $\epsilon$. Let $m$ be such that $x_{m} < \epsilon$. Then let $y$ be a sequence which is same as $(x_{n})$ except at $m$ where it is $y_{m} = x_{m} - \epsilon$. Then $(y_{n}) \in B((x_{n}), \epsilon)$ but is not in $E$.
3:
Let $x \in E$. Then $x = (x_{1}, x_{2}, \ldots )$ with $x_{i} \geq 0$ and the sequence goes to $0$. We will construct a sequence in $E$ going to $x$.
Let $y_{1}$ be the sequence $(x_{1} + 1, x_{2}, \ldots)$ and $y_{2} = (x_{1}, x_{2} + 1/2, x_{3}, \ldots)$ and so on. Then each sequence $y_{j}$ is an element of $E$ and $d(x, y_{j}) = 1/j$ and hence $(y_{j}) \to x$. Thus, $E \subset E^{\prime}$.
Conversely, let $x = (x_{1}, x_{2}, \ldots) \in X$ be such that $x_{n} < 0$ for some $n$. Then one can see relatively easily that no sequence from $E$ can converge to $x$ (since the distance has to be smaller than the value $|x_{n}|$ from some point on). Thus, $E^{\prime} \subset E$.
4:
This follows from 3. Set of limit points of a set is closed and $E$ is equal to the set of its limit points.
Comment: Is $E$ compact ?
Comment: Compact sets are bounded. E is not


How to limit connection speed

Question: I am on CentOS 6.4 and am using Plesk v11.5.30 although this doesn't necessarily need to be done via plesk.
I am looking to limit the connection speed to a specific website. However the only options Plesk gives me are "Maximum bandwidth usage" and "limit connections".
Maximum bandwidth usage is the total bandwidth used by a domain while connections is the number of connections (obviously). What I want to do is limit the speed to 200kb/s irrespective of how many people are accessing the domain. Even if only one person is accessing, I don't want them to be able to use all the bandwidth, I want them to be limited to 200kb/s
Is there a way for me to limit all individual connections to just 200kb/s so that no one can ever use over 200kb/s, but of course if traffic is high they may use less than 200kb/s?
To avoid this being plesk specific, this is what is in my conf and I'm happy to modify it manually if there is some other parameter I can use:
<IfModule mod_bw.c>
    BandwidthModule On
    ForceBandWidthModule On
    Bandwidth all "0"
    MaxConnection all "0"
    BandWidthError 510
</IfModule>

Answer: I've never used this module but the documentation seems fairly straight forward.
The directives are valid inside a <VirtualHost> block and will only apply to that virtual host if so.  It also looks like they don't inherit from higher parts of the config so you should put every relevant directive in the virtual host.
Your current config sets the bandwidth limit to "0" which means no limit.  You want 200KB (I presume you meant kilobytes and not kilobits).
Put this in the virtual host you want to limit:
BandwidthModule On
ForceBandWidthModule On
Bandwidth all 204800

The default MinBandwidth is 256 bytes/s so you can handle 800 simultaneous users before any of them will start getting error messages.  If you think 256 bytes/s is a bit low, you can also add MinBandwidth all 1024 which will mean that when you have more than 200 simultaneous requests the 201st will get an error message instead of the page they requested and all of the 200 before that will be guaranteed at least 1KB/s.
I don't usually bother with those <IfModule> blocks because all they do is hide your mistakes and make you think mod_bw is working when it hasn't even loaded.
Answer: I figured this out using LargeFileLimit:
<IfModule mod_bw.c>
BandwidthModule On
ForceBandWidthModule On
Bandwidth all "52428800"
MaxConnection all "400"
LargeFileLimit * 1024 204800
BandWidthError 510
</IfModule>

This will mean that the domain is limited to 50mb bandwidth (52428800), that it can only have 400 connections at once and that any files over 1mb will be limited to 200kb/s (204800).
For anyone reading this later you can also put an extension instead of * to limit just zips,rars,avis or whatever.
Comment: Hi, can you tell me where you found the file to put that config in? Thanks

How to limit connection speed


The group of rigid motions of the cube is isomorphic to $S_4$.

Question: I want to solve the following exercise from Dummit & Foote. My attempt is down below. Is it correct? Thanks!

Show that the group of rigid motions of a cube is isomorphic to $S_4$.

My attempt:
Let us denote the vertices of the cube so that $1,2,3,4,1$ trace a square and $5,6,7,8$ are the vertices opposite to $1,2,3,4$. Let us also denote the pairs of opposite vertices $d_1,d_2,d_3,d_4$, where vertex $i$ is in $d_i$. To each rigid motion of the cube we associate a permutation of the set $A=\{ d_i \}_{i=1}^4$. Denote this association by $\varphi:G \to S_4$, where $G$ is the group of those rigid motions, and we identified $S_A$ with $S_4$. By definition of function composition we can tell that $\varphi$ is a group homomorphism.
We prove that $\varphi$ is injective, using the trivial kernel characterisation:
Suppose $\varphi(g)=1$ fixes all of the the pairs of opposite edges (that is we have $g(i) \in \{i,i+4 \}$ for all $i$, where the numbers are reduced mod 8). Suppose $g$ sends vertex $1$ to its opposite $5$. Then the vertices $2,4,7$ adjacent to $1$ must be mapped to their opposite vertices as well. This is because out of the two seemingly possible options for their images, only one (the opposite vertex) is adjacent to $g(1)=5$. This completely determines $g$ to be the negation map which is not included in our group. The contradiction shows that we must have $g(1)=1$, and from that we can find similarly that $g$ is the identity mapping. Since $\ker \varphi$ is trivial $\varphi$ is injective.
In order to show that it is surjective, observe that $S_4$ is generated by $\{(1 \; 2),(1 \; 2 \; 3 \; 4) \}$ (this is true because products of these two elements allow us to sort the numbers $1,2,3,4$ in any way we like). We now find elements in $G$ with images under $\varphi$ being those generators. Observe that if $s$ is a $90^\circ$ rotation around the axis through the centres of the squares $1,2,3,4$ and $5,6,7,8$, such that $1$ is mapped to $2$, followed by a rotation by $120^\circ$ around the line through $2,6$ (so that $1$ is mapped to $3$), we have $\varphi(s)=(1 \; 2)$ .Observe also that if $t$ is $90^\circ$ rotation around the axis through the centres of the squares $1,2,3,4$ and $5,6,7,8$, such that $1$ is mapped to $2$, we have $\varphi(t)=(1 \; 2 \; 3 \; 4)$. Now if $\sigma \in S_4$ is any permutation, we express in as a product involving $(1 \; 2),(1 \; 2 \; 3 \;4)$, and the corresponding product involving $s,t$ is mapped to $\sigma$ by $\varphi$. This proves $\varphi$ is surjective. We conclude that $\varphi$ is an isomorphism, so $G \cong S_4$.
Comment: It is hard to follow your surjectivity argument without a diagram indicating labeling the vertices.  If this is a homework assignment, I would suggest including one in your write up that you turn in.  It sounds like your $s$ sends $4$ to $3$ (the first transformation sends $4$ to $1$ and the second transformation sends $1$ to $3$), so it does not appear to be what you want in order for $\phi(s) = (1, 2)$.  There's an easier proof for surjectivity (see answer below).
Comment: @MichaelJoyce I'm sorry, it should have been $1$ mapped to $8$ in $s$.
Answer: The standard way of proving that $\phi$ is surjective is the following.  First, show that $G$ has $24$ elements.  Then, since you've proven that $\phi : G \rightarrow S_4$ is an injective function between two sets of the same cardinality, it follows that $\phi$ must be surjective.  (For if not, the image of $\phi$ would have $< 24$ elements in it, so by the pigeonhole principle, there would be some $\pi \in S_4$ with at least two distinct elements mapping to it via $\phi$, contradicting the injectivity of $\phi$.)
To show that $G$ has $24$ elements, use the orbit-stabilizer theorem.  For example, $G$ acts on the set of $6$ faces of the cube, and the stabilizer of a face is a cyclic group of order $4$ generated by a $90^{\circ}$ degree rotation.  Thus, $G$ has $6 \cdot 4 = 24$ elements.  You could also use the action of $G$ on vertices ($8 \cdot 3$), edges ($12 \cdot 2)$ or diagonals ($4 \cdot 6$) instead of faces.
Comment: Thank you! This is great because I already have that $|G|=24$ from a previous exercise.
Comment: How could you say that there are $6\times 4 $ elements,as you count identity for each correspondence faces? I mean , I don't understand, are these $6$ identities corresponding to their respective cyclic subgroups will be different?         Technically ,in my count there are $(6\times 3 )+$ identity $= 19$ elements. Right??
Comment: You're misinterpreting the Orbit-Stabilizer Theorem. It does NOT assert that G is equal to the union of the stabilizers of the 6 faces. It simply says here that the order of G is equal to the cardinality of any stabilizer of the 6 faces (in fact, the stabilizers are all conjugate to each other, so have the same cardinality) times the number of faces.
Answer: Surjective: The group of rigid motions of a cube contains $24$ elements, same as $S_4$. Proof - A cube has $6$ sides. If a particular side is facing upward, then there are four possible rotations of the cube that will preserve the upward-facing side. Hence, the order of the group is $6\times 4 = 24$.
Injective: A cube has $4$ diagonals. For one of the diagonals's head and tale attach $1$, for another $2$ and so on. We choose tale and head of a diagonal same, since there is no way to have rigid motion for a cube to change head and tale and still the diagonal remains in same orientation. For first diagonal you can attach any one of $1$, $2$, $3$, or $4$, as you could choose for first place in $S_4$. For the second diagonal it remains $3$ numbers to choose to attach as same for the second place in $S_4$. And till the last one, and we are done.
Answer: Let's imagine a die with faces numbered 1 through 6.
First of all, a cube has six faces, so $|G|$ divides $6! = 720$ .
However, our flips need to preserve pairs of opposite faces (which must add up to 7).
That means once we know where faces 1, 2, and 3 are sent, we've completely determined what happens to the die.
One can be sent anywhere, two can be send to the remaining four places, and three can be sent to the remaining two places.
So, we get $6 * 4 * 2 = 48$.
However, half of those transformations change the chirality of the die and do not correspond to rigid motions in $\mathbb{R}^3$, so we get
$$ 48 / 2 = 24 $$
We can prove that the group of rigid motions that preserve a cube is isomorphic to $S_4$ by establishing an isomorphism between two-line notation on four elements and plus-minus two-line notation on three elements, with an even number of minus signs.
I haven't seen plus-minus two-line notation before; it's something I made up for the purposes of this problem. We're really just decorating the bottom row with coefficients drawn from the group $\{-1, +1\}$ and saying those coefficients commute with everything when composing two plus-minus permutations given in tabular form.
Here's a permutation of $\{a, b, c, d\}$.
$$ \begin{pmatrix} a & b & c & d \\ b & c & a & d \end{pmatrix} $$
Here's the corresponding plus-minus permutation of $\{a, b, c\}$.
$$ \begin{pmatrix} a & b & c \\ +b & +c & +a \end{pmatrix} $$
Here's another permutation of $\{a, b, c, d\}$. This time it doesn't fix $d$.
$$ \begin{pmatrix} a & b & c & d \\ d & b & c & a \end{pmatrix} $$
Here's the corresponding plus-minus permutation of $\{a, b, c\}$
$$ \begin{pmatrix} a & b & c \\ +a & -c & -b \end{pmatrix} $$
In the original permutation $a$ is sent to $d$, so $d$ is replaced with $a$. $b$ and $c$ each get a minus sign and get swapped. $a$ gets a $+$ sign.
So, more generally, here's the map $\varphi$.
Let $\pi$ be a permutation of $\{a, b, c, d\}$.
If $\pi$ fixes $d$, $\varphi(\pi)$ sends each $x$ among $a, b, c$ to $+\pi(x)$.
If $\pi$ does not fix $d$, $\varphi(\pi)$ sends $\pi^{-1}(d)$ to $+z$ with $z$ being the sole element $\{a, b, c\} \setminus \pi(\{a, b, c\})$. $\varphi$ swaps and negates the remaining elements.
We invert $\varphi$ by noting the number of minus signs in our plus-minus permutation of $\{a, b, c\}$. If it is $0$, we add another row sending $d$ to $d$.
If it is nonzero, we find the single row with a positive entry, exchange that entry and $d$ in the bottom row, and then remove all the plus signs and minus signs and swap the two entries that had minus signs.
Definition of inverse in two-line notation.
You exchange the top and bottom rows.
$$ \begin{pmatrix} a & b & c & d \\ b & c & a & d \end{pmatrix} $$
This becomes
$$ \begin{pmatrix} b & c & a & d \\ a & b & c & d \end{pmatrix} $$
Which normalizes to
$$ \begin{pmatrix} a & b & c & d \\ a & c & b & d \end{pmatrix} $$
Definition of inverse in signed two line notation.
You exchange the top and bottom rows, and then move the signs to the bottom (this only works because in the group $\{-1, 1\}$, all the elements are involutions).
$$ \begin{pmatrix} a & b & c \\ +b & +c & +a \end{pmatrix} $$
Becomes
$$ \begin{pmatrix} +b & +c & +a \\ a & b & c \end{pmatrix} $$
Becomes
$$ \begin{pmatrix} b & c & a \\ +a & +b & +c \end{pmatrix} $$
Which normalizes to
$$ \begin{pmatrix} a & b & c \\ +c & +a & +b \end{pmatrix} $$
Lemma 51: $\varphi$ is a bijection.
Start off with a two-line permutation of $\{a,b,c,d\}$, $\pi$.
Suppose $\pi$ fixed $d$. $\varphi(\varphi(\pi))$ is equal to $\pi$, since we add in $+$ signs and then remove them in the first three columns and $d$ is fixed.
Suppose $\pi$ does not fix $d$. Suppose without loss of generality that $\pi(a) = d$. $b$ and $c$ will be sent to negative letters and $a$ will be sent to the sole positive letter. The sole positive entry in the second row of $\varphi(\pi)$ will be sent back to $d$ in $\varphi(\varphi(\pi))$. The other entries will be translated correctly. Additionally the $d$ column will get the remaining letter.
Since the domain and codomain of $\varphi$ are both finite, $\varphi$ is a bijection.
Lemma 101: $\varphi$ is an injective group homomorphism and hence an isomorphism.
The identity element $\begin{pmatrix} a & b & c & d \\ a & b & c & d \end{pmatrix}$ is sent to the identity element $\begin{pmatrix} a & b & c \\ +a & +b & +c \end{pmatrix}$.
Let $\pi$ be a permutation of $\{a, b, c, d\}$. $\varphi(\pi^{-1})$ is equal to $\varphi(\pi)^{-1}$.
Suppose $\pi$ fixes $d$. Adding $+$ signs to the bottom row and removing the last row, as an action, commutes with swapping the rows and renormalizing, as an action.
Suppose $\pi$ does not fix $d$.
$\pi$ has the form $\begin{pmatrix} a & b & c & d \\ \pi(a) & \pi(b) & \pi(c) & \pi(d) \end{pmatrix}$
We can perform the transformation operation on the entire full table without removing the column immediately. Let $\varphi(\pi, x)$ mean $\varphi(\pi)(x)$, but look nicer.
$$ \begin{pmatrix} a & b & c & d \\ \varphi(\pi, a) & \varphi(\pi, b) & \varphi(\pi, c) & \varphi(\pi, d) \end{pmatrix} $$
Let $\varphi(\pi, d)$ be $+d$ always.
From this form, it should be clear that performing the inverse and renormalizing commutes with removing the last column.
Now, I'll cover composition in general.
First, I observe without explicit proof that $\varphi$ is a homomorphism when restricted to permutations of $\{a,b,c,d\}$ that fix $d$.
Let $\tau$ be a transposition involving $d$.
I will now prove that $(\pi\tau)^\varphi = \pi^\varphi\tau^\varphi$, note that $fg$ is equivalent to $g \circ f$ in function notation.
Suppose without loss of generality that $\tau$ exchanges $a$ and $d$.
$$ \tau^\varphi = \begin{pmatrix} a & b & c \\ +a & -c & -b \end{pmatrix} $$
Let suppose $\pi$ fixes $d$.
This leaves six possible permutations

$ \begin{pmatrix} a & b & c & d \\ a & b & c & d \end{pmatrix} $
$ \begin{pmatrix} a & b & c & d \\ a & c & b & d \end{pmatrix} $
$ \begin{pmatrix} a & b & c & d \\ b & a & c & d \end{pmatrix} $
$ \begin{pmatrix} a & b & c & d \\ b & c & a & d \end{pmatrix} $
$ \begin{pmatrix} a & b & c & d \\ c & a & b & d \end{pmatrix} $
$ \begin{pmatrix} a & b & c & d \\ c & b & a & d \end{pmatrix} $

For each of these, we check the theorem by hand.
I'll check case #5 explicitly.
$$ \begin{pmatrix} a & b & c & d \\ c & a & b & d \end{pmatrix}^\varphi \begin{pmatrix} a & b & c & d \\ d & b & c & a \end{pmatrix}^\varphi \;\;\text{equals} \\
\begin{pmatrix} a & b & c \\ +c & +a & +b \end{pmatrix} \begin{pmatrix} a & b & c \\ +a & -c & -b \end{pmatrix} \;\; \text{equals} \\
\begin{pmatrix} a & b & c \\ -b & +a & -c \end{pmatrix} \;\;\text{equals} \\
\begin{pmatrix} a & b & c & d \\ c & d & b & a \end{pmatrix}^\varphi \;\; \text{as desired}
 $$
We chose the transposition to involve $a$ arbitrarily at the beginning, so we're done.
Thus, as desired, the symmetries of a cube as a group are isomorphic to $S_4$


Is it possible to pop the UINavigationController twice?

Question: Is it possible to pop the navigation controller twice? I have this navigation structure:
View One ----> View Two ----->   View Three
What I'd like to accomplish is that by the tap of a row on View Three, go back directly to View One. I've done it from Three to Two via protocol-delegate, but setting the delegate in view One doesn't work and setting two consecutive delegate-protocol both poping the navigation controller, gives me error: nested navigation controller activity (or something similar).
Any help would be appreciated. Thanks in advance!
Answer: There is a few pop options
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated

The first pops the top controller.
The second allows you to pop the whole stack off to get to the root.
The third allows you to pop to any viewController you have a reference to. You can get the viewController with self.navigationController.viewControllers and then work with the array to get the specific viewController you want to pop to
Answer: Use the following code. You can use any number instead of -3 to pop to a different level.
Obj-C:
ViewController *View = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-3];
    [self.navigationController popToViewController:View animated:YES];

Swift 3.0*:
let controller = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 3]
self.navigationController?.popToViewController(controller!, animated: true)

Answer: You can try this
[self.navigationController popToViewController:[[self.navigationController viewControllers] objectAtIndex:1] animated:YES];

Hope it Helps!!
Answer: 'self' seems to be released after first pop
UINavigationController *navigationController = self.navigationController;
[navigationController popViewControllerAnimated:NO];
[navigationController popViewControllerAnimated:YES];


exact homology sequence associated to a fibration

Question: let $p:E\rightarrow B$ be a fibration with fiber $F$, ($E$ and $B$ are cw complexes). $B^k$ denotes the $k$-skeleton of $B$.
1) what does this sentence mean :"we denote the restriction of $E$ to $B^k$ by $E^k$".
2) why there is an exact sequence
$$\cdots \rightarrow H_{i+1}(E^{k+1},E^k)\rightarrow H_i(E^k,F)\rightarrow H_i(E^{k+1},F)\rightarrow \cdots$$
3)What is a trivialization of $E$ over the $(k+1)$-cells $D_\alpha^{k+1}$ of $B^{k+1}$
from which we conclude that
$$H_{i+1}(E^{k+1},E^k)=H_i(\sqcup_\alpha D_\alpha^{k+1}\times F \, , \, \sqcup_\alpha S_\alpha^{k}\times F)$$
Comment: The definition of $E^k$ just means that it is the elements of $E$ that get sent to $B^k$.
Answer: To answer (1), the restriction is defined by $E^k=p^{-1}(B^k)$, which forms a fibration over $B^k$.
To answer (2), this is the long exact sequence for the triple  $F\subset E^k\subset E^{k+1}$.
Finally, to answer (3), a trivialization of a fibre bundle means that it is isomorphic to a "trivial" fibre bundle, which is just a product of the base with the fibre. (I'm not sure why we switched to a bundle rather than a fibration.) In any event, the fibre bundle is a product when restricted to the interior of each $k+1$-cell, so that it looks like $D^{k+1}\times F$ on that cell. When we take the relative homology $H_{i+1}(E^{k+1},E^k)$, we are modding out by the boundary of each $k+1$-cell so that the result is the same as looking at each cell separately, noticing that $E^{k+1}$ is a product there, and then modding out by the boundary, which gives the right-hand side of the formula you stated.