Server and Network Dashboard

Question: We have a Network Operations Center with a dozen large, widescreen displays showing us various performance graphs, server and network equipment alarms, and status pages.  I lot of the pages were obviously not designed for viewing on a static display.  Does anyone have a similar setup where they have found a particular tool or package that excels at displaying data?  I'm thinking that a bit of custom programming and maybe something that can scroll text, show dials, flashing lights, and whatnot would produce what I'm looking for, but I don't know where to start.  If anyone has any dos or don'ts or success with particular products, that would be a big help.
UPDATE: It seems what I am looking for is a dashboard creation tool.
Comment: What is the source of most of the data?  I assume you are using several different monitoring/alerting tools.  I would bet that most of them have add-on applications for visualization.
Comment: Our main sources of data are SPECTRUM and Nagios.
Answer: What I have done is I get as much of it into a web browser as I can.  Then I use Firefox, IE-TAB, and Tab mix plus to display the data.
Tab mix plus allows you to auto update and rotate the tabs on a schedule.
IE-Tab allows you to display IE windows inside the tabs so that TMP can do the auto rotate and update.
Then you can display all of the MRTG, CATI, NAGIOS, What'sUp Gold, wireless monitors you want and it auto-rotates, auto-updates and is shiny...:)
We have a developer that builds WPF apps for fun so when I want shiny he builds those for me.
Comment: nice. thanks for the idea. I have been thinking about how to do this for a while
Answer: We had too many displays and not enough useful info, so we totally cheated. We found an interesting LCARS-based screen saver (looks like the displays from Star Trek) and ran it on one of the idle displays. That was the one the bosses watched most.
Comment: Yup. Seems that the biggest need for the big screen is the bosses wanting a showplace. I recall one job where we put up some fake-but-nice-looking do-nothing displays.

Our *real* status system was the backround color. Green for nominal ops; yellow if we had probs that would make at least one director-level person take note; red if it would get 3 or more directors angry.

Obviously, black for an all systems outage. Ha-hah.
Answer: Computers are far better than I at analyzing data. I personally prefer systems like OpsView that digest situations and offer a multifaceted interface. Monitoring stats are filtered for abnormal conditions, and individual alerts are delivered to admins responsible for the system. There's an overall health dashboard that's viewable by helpdesk and management that gives an impression of how bad an outage is and whether anyone who can fix it is working on it yet. They put it on rotation on the big screen as something you can see at a glance, not something you stare at all day. Scrolling text and flashing lights aren't how salaried employees should interface with your monitoring systems.
Conrad Albrecht-Buehler has a Google Techtalk ("Making Monitoring Suck Less") that discusses the merits and shortcomings he sees in current dashboard UI design, and proposes some improvements. I don't know if he's published code or even his thesis. The general idea is simple:

You define situation monitoring as capturing a set of signals about a state. Load, free disk space, network traffic, or even higher level things like forum posts per hour.
Then you define a heed function that maps the wide input signal from 0 to 1, with 0 being "ignore" and 1 being "zomg!". In terms of Nagios, he replaces the WARNING state with a WARNING integer.
Finally you define a a aggregator to summarize and prioritize those WARNING signals.

As far as specific tools you'd use to write your own monitoring system, Nagios scripts have a decent interface (probably this is where you'd glue in a HEED mapping if you like it), storing signals can be done with rrdtool, and you can generate graphs from that, and there's a Django app called Graphite that renders rrd databases. There's also Nagvis:

NagVis is a visualization addon for the well known network managment system Nagios.
NagVis can be used to visualize Nagios Data, e.g. to display IT processes like a mail system or a network infrastructure.
Answer: I wrote my own Nagios visualisation after finding out that none of the easily found versions can handle hundreds of hosts with tens of thousands of checks. (To release the code I need a few people who want to try it outside of my environment so I can convince the bosses)
Even the few that might not break required manual configuration that our nagios config generator couldn't be perverted to do.
My visualisations are use on OS X and Linux, oddly the only OS X browser with a working fullscreen mode is Opera, neither Safari (and that includes webkit) nor FireFox do.
A few general tips though:

Big fonts, to the point of automating layouts so they get bigger if there's less to display
Use sorting so the biggest problems are first
Use META refresh, not javascript for reliability
Do your best to minimise the maintenence needed, better to be getting warned about a system not yet in production then finding out a year in that it was never added to the displays
SVG can be wonderful, although they seem to get corrupted over time (we use a simple graphic of a state as an additional visual cue)
Answer: I don't know of any existing packages, but if you're happy coding stuff and your NOC is Windows-based, you might be interested in the PowerShellToys that /n software have announced.  There's a post on the PowerShell blog providing more information and links to each PowerShellToy.  My first thought on hearing about these was that they would be ideal for creating a dashboard for monitoring servers and whatnot.
Comment: While the systems running the displays are Windows-based, the data comes from mostly Linux based systems.  I'm not sure if this would help.  The idea of a dashboard is exactly what I'm looking for though.
Answer: We use Mercury (now HP)'s BAC tools for our dashboards. I can take counters, alerts, etc from SO many sources, crunch their stats and dashboard those stats in a variety of ways. I'll warn you know though, this is a high-end solution - very spendy.

Server and Network Dashboard


Como capturar dados do response error do axios quando usuário não possuir conexão?

Question: Estou utilizando o interceptor de responses do axios para tratar erros nas requisições.
Estou utilizando atualmente desta forma:
const api = axios.create({
  baseURL: 'http://localhost:3333'
});

api.interceptors.response.use(
  function (response) {
    // Qualquer status code que for entre o range 2xx ativa essa trigger
    // Mostra o toastr de success com mensagem vinda do backend
    ...
  }, function (error) {
    // Qualquer status code que for fora do range 2xx ativa essa trigger
    // Mostra o toastr de erro com mensagem vinda do backend
    ...
  }

Como podem ver, quando ocorre um erro no meu backend, ele entra no error e eu consigo capturar os dados do erro e mostrar um toastr acessando error.response.data. Porém como posso captar os dados de erro quando o usuário não possui conexão?
Tentei:
console.log(error)

É printado:

É possível acessar apenas essa mensagem de erro? "Network Error" ou algo semelhante deste erro?
Tentei também:
console.log(error.response) // printa undefined

Comment: Tenta só com `console.log(error)`.
Answer: Após pesquisar um tempo, encontrei essa issue no github do axios onde a mesma pergunta foi feita.
Como dito nas respostas, é impossível detectar erros de rede no navegador, portanto o axios responde com uma mensagem de erro genérica

"Error: Network Error"

Onde a mesma não possui um status especifico, portanto, bastou fazer a seguinte verificação:
if (!error.status) {
    // Usuário não possui internet, mostra toastr de erro
}


How to transcribe key(or mode) signature to word

Question: Here is my method and it work 80% of the time but sometimes it didn't work. What do I do wrong?
I know how to do all the major no problem.
so:

C = 0
D = 2#
E = 4#
F = 1b
G = 1#
A = 3#
B = 5#

and if there is a lot of flats i will 7-NUMBER of flat = k
and if say k = 3 i will know it is Ab Maj.
The question I am doing right now would give me a signature I will count how many sharp/flat are there. And I will adjust accordingly so:

Ionian NO-CHANGE
Dorain +2#
Phrygian +4#
Lydian +1b
Mixolydian +1#
Aeolian +3#
Locrian +5#

and then I just treat it as a major and go from there. so for example Dorian who have 5 flats. I would 5 flats+2 sharps = 3 flats --> 7-3=4 -->Eb Dorian.
then i econunter the fact that there might be possibility where there is lots of sharps and flat and I learned that you can use 12-NUMBER of SHARPS = equivalent number of flats so 8 flat is same as 4 sharps and 8 sharp is also equivalent to 4 flat....
but then I got this question:
which Locrian's signature is 7# so i do 7+5=12 and 12-12=0 so i confidently answer C Locrian.
and it is INCORRECT.
the correct answer is B# locrian and if you work backward it make sense.
what step have I done wrong.
Comment: C and B# are pitch-equivalent.
Comment: The modes are like the "opposite" of the alterations to make a major scale. So the Lydian mode has a #4, not a b4. Mixolydian has a b7, not a #7. And likewise with the other modes.
Comment: @ToddWilcox Okay, here's what OP is proposing. I have a certain key signature, and I want to know which Lydian scale shares that key signature. I add one flat, figure out the major key that new key signature corresponds to, and the tonic of that major key is the root of the dorian scale I'm trying to find. Example: Key of 1 flat. What Lydian scale is that? Add a flat, so now two flats. That corresponds to Bb major. So Bb Lydian is the Lydian scale with one flat.
Comment: @Aaron, but would a musician say that signature(7#) is of a C Locrian or a B# Locrian
Comment: I see. The Locrian scale corresponding to 7 sharps would be B# Locrian. (C Locrian would have 5 flats).
Comment: @ToddWilcox What Math Noob is getting at is the alteration from the key signature to get the mode with the same root note. For example, F Locrian's key signature = F Major's key signature minus one flat.
Comment: @Aaron There's something I'm not getting. If you're right, why does Lydian say "+1b" instead of "-1b"? And ideally it would say "+1#" instead of "-1b" in case there are no flats in the key signature. And even better would be to say "#4" so it's clear which degree of the scale should be sharpened.
Comment: @ToddWilcox Apparently I'm the one not getting it. I misread the +/-. Let me get my head on straight and try again....
Comment: C locrian is five flats, zero sharps. It's the same key signature as Db major/Ionian. Your list of "all the major keys" is missing five of the major keys, since there are 12 total. For instance, Bb major is missing from your list of major keys. The problem is each key signature can indicate one of many keys/modes. So you can't tell exactly which key/mode is indicated by using the key signature alone.
Comment: @Aaron Ok you might be right, that seems to likely be consistent. But also way harder than other ways to do it.
Answer: Seems like sledgehammers and nuts to me!
There are only 7 modes, and 12 major keys that cover 99% of music in major keys.(Minor modes are more complex).
Learn the 7 modes in order - Ionian, Dorian, Phrygian, Lydian, Mixolydian, Aeolian and Locrian.
Learn the circle of 4s/5s, which gives you the number of sharps/flats.
All the modes of any key will contain those same sharps and flats as its Ionian mode.
So, for example, D Ionian, E Dorian, F♯ Phrygian, etc all have the same sharps as each other.
This way may not be exactly mathematical, but it sure works! And probably is just as easy/difficult to administer!
Comment: The question's "...so i confidently answer C Locrian. and it is INCORRECT. the correct answer is B# locrian" heavily implies that, for the asker's purposes, there are more than 12 major keys and enharmonic notes are not treated as the same note.
Comment: @Dekkadeci - true, but pretty impractical, unless we just need a maths formula to tell us something pretty impractical. Can't remember ever playing in B# Locrian. Or any other Locrian, happily!
Answer: Your "12-NUMBER of SHARPS" step to calculate the number of flats intrinsically assumes that enharmonic notes are equivalent. Your "...so i confidently answer C Locrian. and it is INCORRECT. the correct answer is B# locrian" shows that you are in a situation where this is not the case, and enharmonic notes are not treated as the same note.
In order to confidently answer which Locrian scale has a key signature of 7 sharps (assuming you don't subscribe to the alternate theory that the key signature should always reflect the tonic and 3rd scale degree combined), you need to extend your sharps table with this:
F♯ = 6♯
C♯ = 7♯
G♯ = 8♯
D♯ = 9♯
A♯ = 10♯
E♯ = 11♯
B♯ = 12♯
You now go 7 sharps (base) + 5 sharps (Locrian) = 12 sharps and get an answer of B♯ Locrian.
Note how you had to memorize theoretical key signatures in order to calculate that answer. (Truth is, I do not memorize any key signatures with more than 7 accidentals because they virtually never appear in published sheet music: I simply extended the letter name pattern of sharp keys even further in order to finish the sharp table extension.)
Comment: But *memorize*? Heyll, I can't tell you the order of sharps and flats past 4 without actually thinking them out "Up a 4th, down a 5th, um..." I feel like the question for the OP is "why"; it seems more like "because I want to know" than "for ease of music making."
Comment: I did sense the flaw in your system in your question that you didn't have F# = 6# memorized at all, which will bite you in the butt later since 6-sharp key signatures and F sharp major are common enough. This hinted to me that you need to memorize all your key signatures with sharps in them...which I just showed you can lead to needing ridiculous amounts of memorization in order to answer all your scale questions confidently with your current system.
Comment: Key signatures with seven accidentals virtually never appear in printed sheet music, since standard practice calls for the enharmonically equivalent signature with five of the other accidentals instead.  Those with more than seven are probably several orders of magnitude rarer.  Can you name a professionally engraved piece of music that employs such a key signature?  I can't imagine why anyone would write a piece in (any mode of) G sharp major or F flat major.
Comment: @phoog - Yeah, I personally can't, either (for 8 or more accidentals or at least 1 double accidental in the key signature) - the closest I can think of is the first edition of Chopin's Heroic Polonaise I had to study for music history lessons, which notably notates a section in D sharp major but with a 4-sharp key signature.
Comment: @phoog - Professionally engraved scores in the public domain that use exactly 7 accidentals in the key signature are actually not that rare, though: I can think of the Well-Tempered Klavier C sharp major entries and the C sharp major portion of Debussy's Toccata of *Pour le piano* off the top of my head, and a quick search reveals that the 3rd movement, a funeral march, of Beethoven's Piano Sonata No. 12 in A Flat Major is notated in A flat minor and uses a 7-flat key signature.
Comment: @AndyBonner - The back of a blank sheet music booklet I had once had all the major and minor key signatures from 0-7 accidentals inclusive; this is part of why I think memorizing all the major and minor key signatures for 0-7 accidentals inclusive is standard.
Comment: LOL, and I look at that a different way: It's there as a reference so you don't have to! Anyway, if the OP's goal is to generate an algorithm or table and ultimately enjoy having total knowledge of all key signatures and modes, more power to them; I just mean (in agreement with Tim's point) it's kind of an arbitrary goal.
Answer: Personally, I think of this in terms of major and minor being modes (because they are), and then modify major or minor into the various major family or minor family modes:
Major (ionian)

raise the ^4 degree to get lydian
lower the ^7 degree to get mixolydian

Minor (aeolian)

raise the ^6 degree to get dorian
lower the ^2 degree to get phrygian
lower the ^2 and ^5 to get locrian

The practical application of that is some thing like this:

start with the given tonic (this is the likely scenario, someone says, for example, play in F# dorian)
determine the major/minor key signature, dorian is in the minor "family", so get the F# minor key signature, which is three sharps, F# C# G#
determine the ^6 degree relative to tonic F#, that will be some kind of D, specifically by the key signature it is a D natural, raise D natural to D#
F# dorian's key signature is four sharps F# C# G# D#

Your examples of...

Dorian who have 5 flats

...and...

which Locrian's signature is 7#

...seem more like music theory quiz questions, not practical situations. Who says "play in the dorian mode with five flats?"
Nevertheless, the way to answer those questions is still easiest, IMO, by reference to major key signatures first, then the various rotations of the major scale to the diatonic modes.
For example...

five flats is Db major, the dorian mode tonic is the ^2 degree of Db major, which is tone Eb, so Eb dorian has five sharps.
seven sharps is C# major, the locian mode tonic is the ^7 degree of C# major, which is tone B#, so B# locrian has seven sharps.

One comment on your method. I may be misuderstanding it but, this part...

C = 0
D = 2#
E = 4#

...will tell you how to get the major key signature on those given tonics. C major is zero sharps/flats, D major is two sharps, E major is four sharps, etc.
But, your mistake seems to be here...

Ionian NO-CHANGE
Dorain +2#
Phrygian +4#

...moving to relative terms raising two degrees (adding two sharps as you describe it) does not give us the dorian mode, it gives us the major scale on the second scale degree of the starting scale. So, if we were starting on Eb major, for example, F natural is the second scale degree, raising two tones, the Ab and Eb to A natural and E natural, leaving only the B, gives us F major.
If we look at it as Eb major, called Eb ionian, and we want to the dorian scale/key signature on the second scale degree of Eb ionian, there is no change to the scale/key signature. Eb ionian and F dorian are the same collection of tones, just starting on different points. The key signature is three flats, Bb Eb Ab, and the scales are Eb F G Ab Bb C D Eb and merely its rotation F G Ab Bb C D Eb F.
Your second chart would really be...
Ionian NO-CHANGE
Ionian transposed up M2 +2#
Ionian transposed up M3 +4#

...you can use 12-NUMBER of SHARPS...

I don't know why you want a system to handle 12 sharps/flats for key signatures. After seven sharps/flats, key signatures become theoretical key signatures. Those are not normally used, and they wouldn't use up to 12 sharps/flats anyway, they would use double-sharps/double-flats, with only 7 total signs in the key signatures.
Nevertheless, 7 sharps is C# major, 5 sharps is B major, basically adding 7 sharps to a key signature will just add a sharp to the tonic, in other words 5 sharps in B major, add 7 more sharps, it becomes B# major, or add 7 sharps to C# major makes it Cx major.
You sort of 'reset' adding sharps at the F, but make them double-sharps and add 5 of them, so Fx Cx Gx Dx Ax then the rest will be plain sharps until you have 7 total changes to the gamut of letters by fifths FCGDAEB, so E# B#, altogether the key signature of "12 sharps" for B# major is Fx Cx Gx Dx Ax E# B#.
Figuring out a theoretical key signature is the onerous part. But, after determining the theoretical key signature, finding the various theoretical modal key signatures is comparatively easy.
What is the locrian key signature using 12 sharps? 12 sharps minus 7 shaprs is 5 sharps, which is B major, so 12 sharps is B# major. The locrian mode starts on the seventh scale degree of B# major, which is Cx, and so Cx locrian has a key signature of 12 sharps.
There is no practical reason to do that.
The main things to understand for all these aspects of key signatures and modes are:

sharps and flats get added to key signatures by ascending or descending perfect fifths
the modes of any given major key "rotating" up the scale from the tonic are: ionian, dorian, phrygian, lydian, mixolydian, aeolian, locrian

If you become comfortable with those two sequences, it's relatively easy to "find" key signatures.
Comment: M2 = major second, M3 is major third.
Comment: can you explain what M2 and M3 is and why is it that my original second chart is musically incorrect?
Comment: @MathNoob In your second chart, first line "Ionian NO-CHANGE" is that meant to represent a C major scale?
Comment: yes! i try to change everything so we can treat everything like major scale and from there we can identify the signature.(find the base note? some other people suggest that that this is what i am doing?)
Comment: OK, so when going to the next line "Dorain +2#" what is the result you intend in terms of scale and key signature?
Comment: like i sad i want to transpose it in a way so it would correspond to a signature in major and that would be the answer:
Comment: so for example X is a signature and is in Dorian. I want to know how can I transpose it so if i treat this transposed signature as a major the note of this major signature would be the same for X
Comment: It's really unclear to me. So starting with for example D dorian, transpose it up a major second to E dorian, but treat it as major, I guess that would mean D major, D dorian and D major share the same tonic of D. Because you added 2 sharps to D dorian to get D major, you know E dorian's key signature is 2 sharps. Is that your process to get E dorian's key signature?


The Right Triangle Game

Question: I am looking for a deeper understanding, particularly the optimum strategy and the maximum score as a function of grid size, of the following (single-player) game played with an $n$ by $m$ grid:
 ($6 \times 6$ example)

Rules

Start with a grid made of $n$ by $m$ squares and execute as many moves as you can
A move consists of making a single straight cut that cuts off a right triangle with the condition that the cut must start and end on a grid point
Your score is the number of moves you made

Example 1: "Naive" strategy
The naive strategy consists of always picking the move that cuts off the smallest possible right triangle.
For grids larger than $2 \times 2$, the naive strategy is game over after four moves:

Example 2: A better try
The following game run, although it starts by cutting off half the grid, contains twenty moves:

Notes

Although the examples all use a $6 \times 6$ square grid, I am particularly interested also in non-square rectangular boards (where the grid units are still squares, of course).
The triangles cut off in the example games are all isosceles. Note that this is not required by the rules!
Since the smallest triangle that can ever be legally cut off is half of a grid unit, $2nm$ is a trivial upper bound for the maximum score.
Unrelated to the original question, this single-player game can also be converted to an interesting two-player game: Players alternate making moves; the last player to make a legal move wins.

The maximum score function
Let $f(n,m)$ denote the maximum score (number of moves) attainable with an $n \times m$ grid.
The following is known about $f$:
$f(n,m) = f(m,n)$ (symmetry)
$f(n,m) \leq 2nm-1$ (see hardmath's comment)
$f(n,1) = 2n-1$ (see hardmath's comment)
$f(n,2) = 3n$ (can be obtained with some thinking)
$f(1,1) = 1$ (corollary of above formula)
$f(2,2) = 6$ (corollary of above formula)
$f(3,3) = 11$ (obtained by manual trial and error)
$f(4,4) = 16$ (obtained by manual trial and error, corrected by hardmath's comment)
$f(n,m) \ge 2\min(n,m) + 3\max(n,m) - 4$ (see hardmath's comment), in particular
$f(n,n) \ge 5n - 4$
Note that the last bound is actually strict for $1 \le n \le 4$, so this bound (and the associated strategy) might already be the answer to the entire question.
Comment: Maybe you could find the maximum for $1\times1,2\times2,3\times3,\dots$ until you have enough to look it up in the Online Encyclopedia of Integer Sequences.
Comment: It suggests a strategy (in the one-player original Q) of shortening the shorter dimension (say $n \ge 2$) down to 2 by a sequence of $2(n-2)$ moves (bisecting each row along a diagonal), then getting $3m$ moves out of the remaining $2 \times m$ shape.  Thus $f(n,m) \ge 2n + 3m - 4$ when $m \ge n \ge 2$.
Comment: Ah, you mean by slicing off two thin, non-isosceles triangles? True, that works!
Comment: We can reduce $3\times 4$ to $2\times 4$ in 2 moves, taking off the "top" row by bisection along its diagonal.
Comment: @JensRenders:  $f(m,n)\ge2m+3n-4$ was established as a limit by user hardmath. I have verified that **equality** in the extreme value, i.e. $f(m,n)=2m+3n-4$, holds for $2 \le m \le n \le 10$.
Comment: Each successive remnant of the board is necessarily a convex shape, produced from the previous stage by "a single straight cut that... must start and end on a grid point".  If we don't count removing a single final right triangle with such a cut, then the trivial upper bound is really $2nm-1$, attainable if one of the dimension is $1$.
Comment: Question: You say that the cut must start and end in a grid point, but ¿must that grid point be in the shape you have cut so far, or can it be outside?
Comment: I've verified $f(m,n) = 2m + 3n - 4$ as a strict limit for $2 \le m \le n \le 10$ via exhaustive search.
Comment: I'm not sure I understand you correctly. Let's say we have a $3 \times 4$ grid. There is no way of shortening the shorter dimension ($3$) down to $2$ without affecting the other dimension as well.
Comment: Note also that your formula implies that $f(4,4)\geq 16$, while my trials strongly indicate that $f(4,4)=15$.
Comment: @Frentos what do you mean by "strict limit"? Do you mean $f(m,n)\geq2m+3n-4$
Comment: Could you maybe set up a recurrence relation by figuring out the relationship between $f(m,n)$ and $f(m,n+1)$?
Comment: @FranklinPezzutiDyer Well for $2\le m \le n$, the previous comments did observe a recursive strategy that gives $f(m,n)\ge 2+f(m-1,n)$. But can anyone prove this strategy is optimal? (Does the equality hold?) Apply it until $m=2$ to use $f(2,n)=3n$, which finally yields $f(m,n)\ge 2(m-2)+3n$ as already discussed. The problem now is either proving the equality holds (strategy is optimal), or finding a counter-example (a better strategy).
Answer: Given that the board m x n may not necessarily square, perhaps for the non-square boards, you must use a method that treats it as a non square board. Im implying that some of the triangles that are cut off are likely to not be isosceles due to the different dimensions and in fact the most optimal way may be cutting off triangles in the ratio of the rectangle of sorts.
Another possibility is sectioning the rectangular board into a square and non-square board. Then you use the optimal method for solving the square and then continue to cut off right triangles on the left over non-square section
I hope this provides some insight to this problem

The Right Triangle Game


Any way to automatically generate a UML diagram?

Question: I have a MySQL DB and I would like to generate its relational diagram. Is there a tool that can connect to the DB and automatically generate it for me?
Answer: Yes, DEVART's DBForge for MySQL will do this.
There is a free Express edition, I'm not sure it has this functionality, but have a look at: http://www.devart.com/dbforge/mysql/studio/
Comment: Anyway, here it is a list of features/editions - http://www.devart.com/dbforge/mysql/studio/editions.html
Comment: Oh and I'm working on a mac. Which means that I can't use it :(
Comment: I would assume that such a nice feature wouldn't be free or even in the trial lol. Thanks though! If there are any other tools out there please let me know.
Comment: @K-RAN, it's definitely in the trail.
Answer: If you are a happy owner of IntelliJ IDEA Ultimate Edition, you can use its database tools. IDEA is able to connect to databases and build UML diagrams.


PythonAnywhere trying to upload my website

Question: I am trying to upload my web-app on PythonAnywhere, but I am not able to do that.I have tried many ways and also searched on google but I am unable to solve it. Please tell me what I am lacking in or what more information should I add here. I have also added the Error Log from PythonAnywhere. Please someone explain me the error also if possible as what I am doing wrong.
my file structure
|-mysite/
    flask_app.py
    |-templates/
        index.html

run.py
from flask import render_template
from bs4 import BeautifulSoup, element
import urllib2
from flask import Flask
app = Flask(__name__)

@app.route('/')
  def index():
  i=1
  count =1
  items = []
  heads = []
  bodys = []
  writers = []
  dates=[]
  m = 0
  while(i<21):
      url = 'http://www.goal.com/en-gb/rumours/last/168?page='+str(i)+'&ICID=OP'
      response = urllib2.urlopen(url)
      html = response.read()
      soup = BeautifulSoup(html)
      i +=1

      # Collect rumors posts
      rumour_post_tags = soup.find_all("div", {"id":"rumours"})

      for rumour_tags in rumour_post_tags:
          content_tags = rumour_tags.find_all("div",{"class":"rumour-content"})
          for rumour in content_tags:
             items.append(count)
             count +=1
             heads.append(rumour.find("h3",{'class':'column'}).text)
             bodys.append(rumour.find('p').text)
             for sources in rumour.find_all('span',{'class':'column'}):
                 for source in sources:
                     if m % 2 == 0:
                         writers.append(source)
                         m += 1
                     else:
                         dates.append(source)
                         m += 1
  return render_template('index.html',allitems=zip(items,heads,bodys,writers,dates))

index.html
<!DOCTYPE html>

  <title>Goal's Transfer Talks</title>

Transfer Talks

    {% for item,head,body,writer,date in allitems %}

{{ item }}. {{ head }}

{{ body }}

{{ writer }}

{{ date }}

    {% endfor %}

I am getting an error when I am trying to open my website through http://rahul3103.pythonanywhere.com/ which is:
Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Error Log:
2015-07-29 11:17:57,179 :Exception on / [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/rahul3103/mysite/flask_app.py", line 19, in index
    response = urllib2.urlopen(url)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden

WSGI Configuration file:
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project

import sys

# add your project directory to the sys.path
project_home = u'/home/rahul3103/mysite'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from flask_app import app as application

Comment: possible duplicate of [open url from pythonanywhere](http://stackoverflow.com/questions/32597390/open-url-from-pythonanywhere)
Answer: It's because you have a free account and PythonAnywhere only allows access to the internet for a whitelist of sites.
Comment: Is there any other way, i can do that
Comment: Yeah goal.com is not there and my website is live on heroku. Thanks for the help.  [My website](https://footballs.herokuapp.com/)


Prove that $6|a+b+c$ if and only if $6|a^3+b^3+c^3$

Question: $6=2\cdot3$
$a^3+b^3+c^3 = (a+b+c)^3-3(a^2b+ab^2)-3(a+b)^2-3(a+b)c$
So it's divisible by $3$, what about $2$?
Comment: $a^3-a=(a-1)a(a+1).$  At least 1 of the   3 consecutive integers $a-1,a,a+1$ is even.  So $a^3-a$ is even. So $(a^3+b^3+c^3)-(a+b+c)$ is even. Therefore :  $a^3+b^3+c^3$ is even iff $a+b+c$ is even.
Answer: Hint:
$$a^3+b^3+c^3-(a+b+c)=(a^3-a)+(b^3-b)+(c^3-c)$$
But $6|n^3-n=(n-1)n(n+1)$
Answer: By Fermat's little theorem, we have $x^3\equiv x\pmod3$ for every $x$, and of course, $x^3\equiv x\pmod2$. This means that
$$ a^3+b^3+c^3\equiv a+b+c\pmod3$$
and
$$ a^3+b^3+c^3\equiv a+b+c\pmod2,$$
which was what we wanted.
Comment: Wait how is $x^3\equiv x\pmod2$?
Comment: If $x\equiv 0\pmod2$, then $x^3\equiv 0^3\equiv 0\pmod 2$. If $x\equiv 1\pmod 2$, then we get $x^3\equiv 1^3\equiv 1\pmod2$.


Fiction variables?

Question: In every Boolean function $f(x_1, x_2,\ldots, x_n)$, for every $i$  ($1\le i\le n$), $x_i$ is called fiction variable if and only if when for every Boolean assessment for the rest variables $x_1, x_2,\ldots, x_{(i-1)}, x_{(i+1)},\ldots,x_n$ the function has the same value for $x_i=0$ and $x_i=1$.
How many Boolean functions of $n$ variables have no fictional variables?
I have some ideas, but don't know how to prove it "formally". Any help would be greatly appreciated.
Answer: I think the question is how many Boolean functions of $n$ variables have no fictional variables.  This can be answered using the inclusion-exclusion principle.  If you take a subset $S$ of size $k$ of the $n$ variables and ask how many Boolean functions on $n$ variables have at least the variables in $S$ fictional, the answer is the same as the number of Boolean functions on the $n-k$ remaining variables, which is $2^{2^{n-k}}.$  Therefore, the number of Boolean functions on $n$ variables with no fictional variables is
$$
\sum_{0\le k\le n} (-1)^k \binom{n}{k} 2^{2^{n-k}}.\qquad (*)
$$
This is OEIS A000371.
In response to the comment: the inclusion-exclusion principle says that if we have a finite set $U$ of properties and a set of objects, and if the number of objects with at least the properties in the set $T\subseteq U$ is $N(T)$, then the number of objects with none of the properties is
$$
N_0=\sum_{T\subseteq U} (-1)^{|T|} N(T). \qquad (+)
$$
(*) follows immediately from (+) upon letting $\{x_1, \dots, x_n\}$ be the set of variables and letting $U$ be the set {"has at least $x_1$ as a fictional variable", $\dots$, "has at least $x_n$ as a fictional variable"}.  This is because, if $T$ is a subset of $U$ of size $k$, then, as explained above, the set of Boolean functions on $n$ variables with at least the properties in $T$ has size $N(T)=2^{2^{n-k}}$.
To see why (+) is true, take as an example the case where $U$ has size 3.  Then, if we let $X$ be the set of all objects and $A$, $B$ and $C$ be the subsets of $X$ which satisfy the first, second, and third properties of $U$, (+) reduces to
$$
|X\setminus (A\cup B\cup C)|=
$$
$$|X|-|A|-|B|-|C|+|A\cap B|+|A\cap C|+|B\cap C|-|A\cap B\cap C|.\ \  (++)
$$
On the right-hand side of (++), to count the number of objects with no properties, we start with the number of all objects, $|X|$, which is an overestimate.  We then subtract $|A|+|B|+|C|$.  This produces an underestimate, since
$|X|-|A|-|B|-|C|$ correctly counts each object with no properties once and each object with exactly one property $0$ times, but if an object has exactly two properties, it is counted $-1$ times, and if it has all three properties, it is counted $-2$ times.  To remedy this, we add
$|A\cap B|+|A\cap C|+|B\cap C|$.  This results in a count which is correct for objects with no properties, counting them once, or objects with exactly $1$ or $2$ properties, which are counted $0$ times.  However, it overcounts objects with all three properties by counting them once instead of $0$ times.  This is fixed by subtracting $|A\cap B\cap C|$, giving the correct and final form of (++).
The proof of (+) in the general case is similar.  The inclusion-exclusion principle is also often stated in the form
$$
N_{\ge 1}=N(\emptyset)-N_0=\sum_{\emptyset\ne T\subseteq U} (-1)^{|T|-1} N(T),
$$
where $N_{\ge 1}$ is now the total number of objects with at least one property.
Comment: can you explain a bit more how do you get a such answer, please?
Comment: One last question - what did you mean under "properties"...my English is very bad?
Comment: A property is something that might or might not be true of an object, like "being red", "having size at least two", "having $x_1$ as a fictional variable", and so on.
Comment: Thanks again and sorry for the stupid questions.

Fiction variables?


Can I use a dataset even if the observations of a variable are not in the same unit?

Question: I am using a dataset where a variable is "height". However, when I read about the construction of the dataset, it seems that some observations in the dataset are labelled in centimetres and others in hectometres, and I don't know which is which, since it is not given in the dataset. (Otherwise I could simple multiply those in hectometres by 10, of course.) Can I still run regressions, even if all the observations of my variables are not in the same unit? Under which conditions?
Comment: Would your "hectometre" be everybody else's *decimeter*?
Answer: 1 hectometer is 10,000 centimeters. So, assuming the same sort of thing is being measured in each observation (whether it's bugs, people, buildings, or mountains), it should be easy to infer which measurements are in which of the two units, by checking if the order of magnitude is reasonable for the thing being measured. For example, a person could be 180 centimeters tall, but not 180 hectometers tall. (Talk about having your head in the clouds, eh? I'll be here all week.)
Without being able to infer the unit, there isn't much you can do, since you can't even tell which two measurements are equal, and when they're not equal, which is bigger. The most you could do is distinguish positive heights from zero heights from negative heights, which is unlikely to be useful because quantities called "heights" are almost always positive.
If each observation has one or more other measurements that are guaranteed to use the same unit, you can at least examine the ratios of these, which are unit-invariant (the units cancel out in the quotients).
Answer: No. All of your observations must be on the same scale to make mathematical sense of the numbers - there is no "scale" in the model, so "1" can be massively different if one is "1 cm" and the next is "1 hectometer". Without units this data set is worthless.
That said, centimeters and hectometers are massively different, and I urge you to re-evaluate your numbers. 1 hectometer = 100 meters, while centimeters are 1/100 of one meter. Multiplying either by 10 isn't the correct conversion, so I suspect you've misread something.


Bott periodicity and algebraic geometry

Question: It is a theorem that every locally free coherent sheaf on $\mathbb{P}^1$ over an algebraically closed field is isomorphic to a unique sum of sheaves $\mathcal{O}(n)$ for various integers $n$. In particular, the K-ring of locally free coherent sheaves (or all coherent sheaves, $\mathbb{P}^1$ being nonsingular) is isomorphic to $\mathbb{Z}[t, t^{-1}]$.
The topological K-ring of vector bundles on $S^2$ is, by Bott periodicity, isomorphic to $\mathbb{Z}[H]/(H-1)^2$, where $H$ is the canonical bundle. But $S^2$ is homeomorphic to $\mathbb{P}^1_{\mathbb{C}}$.
Every locally free sheaf corresponds to a vector bundle on $S^2$. It follows that the map on the K-groups from locally free sheaves to vector bundles is surjective but not injective.
Questions:

What goes wrong?
Is there a version of Bott periodicity for algebraic varieties (or schemes)? (I.e., relating K-groups of $X$ and $X \times \mathbb{P}^1$.) I understand that there is one for the Picard groups.
Comment: There are less algebraic/holomorphic sections than continuous ones, so there is nothing wrong in (1)!
Comment: As for periodicity... Well, it is complicated! :) You could do much worse than read Max Karoubi's note on *Bott periodicity in Topological, Algebraic and Hermitian K-theory*, which you can find in his homepage at Jussieu.
Comment: @Mariano: Thanks! I agree with your first comment, but simply was used to things working out very similarly in algebraic topology as in topology (e.g. the isomorphism between sheaf cohomology and singular cohomology, the analogy between etale neighborhoods and neighborhoods in the complex topology, etc.). I take it that if you consider the Grothendieck ring of *holomorphic* vector bundles, it should be the same as the algebraic one, no? (This is probably in GAGA, right?). Also, thanks for the reference.
Answer: It is not true that the Grothendieck ring of coherent sheaves on $\mathbb{P}^1$ is isomorphic to $\mathbb{Z}[t, t^{-1}]$. Although $\mathcal{O} \oplus \mathcal{O}(2)$ is not isomorphic to $\mathcal{O}(1) \oplus \mathcal{O}(1)$, they do have the same class in $K^0$.
The definition of the Grothendieck group of coherent sheaves on a scheme $X$ is that it is generated by isomorphism classes of coherent sheaves, modulo the relation that $[A] + [C] = [B]$ whenever there is a short exact sequence
$$0 \to A \to B \to C \to 0.$$
In particular, we have the short exact sequence
$$0 \to \mathcal{O} \to \mathcal{O}(1)^2 \to \mathcal{O}(2) \to 0,$$
where the maps are given by $(x \ y)$ and $\binom{-y}{x}$.
This makes $K^0$ into $\mathbb{Z}[t, t^{-1}]/(t^2 - 2t +1) \cong \mathbb{Z}[u]/u^2$, just like you wanted.
When working in the categories of smooth or of topological vector bundles, all short exact sequences split, so you can get away with defining $K$-theory with direct sums. You can't do that in the coherent or the algebraic categories.
Comment: Ah, very nice---thanks for the answer.

Bott periodicity and algebraic geometry


Voice - Trouble with high notes

Question: I'm finding I'm having a lot of difficulty singing notes that are in the upper range. I have a voice teacher, and she's giving me warmups and tips about keeping my throat open. I've made some progress - initially I wasn't able to hit the notes at all - but I still feel a great tightening in my throat, almost a choking feeling when I try to sing the high notes. I also have to sing louder to get the note out. It sounds strained and forced.
Here are some of the tricks I've tried:
smile (helps a little)
pretend I'm yawning (make my voices sound wierd)
sing through my nose (helps, but sounds nasal and feels like I'm holding my breath - not really open).
How can I sing high notes with a nice, relaxed voice?
Comment: What voice type are you, and what range is causing problems? Is it the "normal" upper end of your range, or is it "above" the normal range?
Answer: Every singer who has ever gotten voice lessons deals with this. Do not be upset if it takes considerable time and practice for you to learn how to sing the high notes freely and easily.
If you keep practicing regularly and carefully, you will get better at it over time. There are certain techniques you can practice to make the high notes sound better, but it all comes down to consistent practice and help from your teacher to overcome problems when you get stuck.
Your vocal tract contains many small muscles, most of which you aren't conscious of using when you sing. The more you sing, the more you learn how to be aware of them and control them. As you do this, you can expand your range and improve your tone and your phrasing. Singing is a sort of an athletic endeavor, on a very subtle scale. You can build up strength in your vocal tract, or fatigue or injure it if you are not careful.
There are some different theories as to how to go about improving the high notes. Sometimes we refer to these as ideas about "voice placement". You just have to find out what works best for you. Your teacher can help you become aware of the position of your larynx and soft palate, and how to control them, for instance, as you form each note, and of how to modify the vowel sounds of high notes to make them easier to sing and to resonate better.
I'm a tenor soloist, and I studied voice at university. Almost 25 years ago when I was about to leave college, I sang a solo in front of all the students of my voice teacher, and in this solo I hit a high B-flat. A young man who had just enrolled in the school as a first-year student came up to me and said, "How can you sing those high notes and make them sound so good?"
I looked at him and said, "You practice every day for three or four years."
Even if you learn good techniques, you have to patiently practice them to get results.
Answer: It is quite normal to have to sing louder to sing high notes, especially when one is just starting to learn how to sing that high! It's very hard to sing high and quietly at the same time.
The key to singing high is to prepare in advance: if you're not ready to sing the high note at the start of the phrase, the high note probably will not sound very good. In part, this means that you can't bring your "chest tone" up to the top of your range. One way to prepare is to breathe at the beginning of the phrase as if the first note you were going to sing is the high note. Then your system is more easily aligned for the high note than if you just try to leap to it in mid-phrase.
One important piece of advice to remember is that what you hear is not what other people hear. Your voice vibrates inside your head, creating additional frequencies in your ear, and thereby changing the timbre. When you are singing high notes properly, the sound may be very different from what you're used to when singing in chest tone, and it may sound quite "small" in comparison. However, when properly resonating, they can be just as loud!

Voice - Trouble with high notes


We love the Second Viennese School, but daughter's practice of Boulez's music is wearying us. How can we appreciate Boulez?

Question: We love and listen to the Second Viennese School like Berg, Schoenberg, Webern — even before my daughter was born! My daughter's studying music at university. To guard privacy, I don't want to write more details on her or our family.
But starting 2019, she's been practicing many pieces composed by Pierre Boulez — and this Ultraserialism is maddening my husband and me! It sounds like random notes and/or noise to us! We haven't confronted her, because she knows more about music, and we know Boulez is a world famous composer and conductor. Boulez conducted "Classical" and Romantic tonal music like Beethoven, Berlioz, Haydn, Mahler —  so this emperor is wearing clothes??!?? Boulez doesn't look like a sham or phony, and we're taking Boulez's music in good faith.
But how can we learn  Ultraserialism? Since 2019, we've watched Boulez's music on YouTube and listened to recordings. But like many others, we still can't "GET" Ultraserialism. When asked in 1999, why so few major pieces of the 1950s and 1960s had become repertory, Boulez replied

"Well, perhaps we did not take sufficiently into account the way music is perceived by the listener" (as cited in Alex Ross's The Rest is Noise, 2007, p. 571).

The Music SE question My child's violin practice is making us tired, what can we do? is similar. But the issue here is not my daughter's practice, but THE ULTRASERIALIST COMPOSERS she's practicing.
Observation on June 20 2021.
I don't know if the responders below will see this, but I found — perhaps too late — another quotation by Boulez rebuffing his own Ultra Serialism on Wikipedia. theartsdesk Q&A: Composer Pierre Boulez | The Arts Desk

Would you rather not have this piece [Referring to Boulez's Piano Sonata no. 2] played any more.
I am not terribly eager to listen to it. But for me it was an experience that was absolutely necessary.
Comment: @Clockwork - it's the story about the Emperor's new clothes. As in 'I don't understand something, so it must be good' in a nutshell.
Comment: @NeilMeyer She can, but that's not the principal issue in this post. Issue is how husband and I can appreciate Boulez and Ultra Serialism!
Comment: why cant she practice at her conserve, even if she lives in the city where she studies music, the conserve should have ample practice facilities for her to practice in. You can make a case that she needs to fully immerse herself in music to get the most out of music school and you cannot fully do it when you are still living at home
Comment: It's a Marmite situation. Love it, hate it, that most often cannot change! My problem with it is not being able to tell if mistakes have been made... No answer, just a comment.
Comment: "so this emperor is wearing clothes??!??" I might not have fully understoodd the meaning of that question, I think. At least, I don't seem to be able to make a connection between that, the previous sentence and the main question.
Comment: Is she practicing in her own room, in the living room or somewhere else that makes it audible from anywhere in the entire house? Is there a place in your home where she can practice without neither of you hearing it? Like a room with good noise insulation.
Comment: You may get more relevant answers by posting on https://musicfans.stackexchange.com/ - if you do so, please also leave a link here because I'm also interested in what people have to say on this topic.
Comment: @Kidburla Thanks. done! https://musicfans.stackexchange.com/q/12011.
Answer: Well, the way you phrase this, it is a "music appreciation" question for which there is different StackExchange group.
But the real question I see here is more one of rehearsal hygiene.  A professional music career requires an exercise regimen that is not expected to be attractive to witnesses, including your daughter's teachers who just get an occasional sample of the progress.  And of course where you are practising individual parts of pieces arranged for multiple performers, it very much depends on the kind of music whether the part gives a good foreshadowing of the larger whole it is part of.
So the question is whether you can find an arrangement where a good part of the time your daughter is practising, you just don't get to hear her.
There may be still a third aspect, namely whether the skills and experience your daughter acquires are sought after enough that her education will enable her to a career she considers fulfilling and that is able to meet her financial needs.  Of course, this is a general problem of becoming a professional musician.  In her case, it would definitely also involve whether she can bring something into this kind of music that gives the listener a better appreciation than what he gets his ears on otherwise.
There is some music where metering your progress in the lens of audience appreciation may start making sense (or at least being forward-pointing) earlier.  But that's to a good degree your tough luck: in the end, it is mostly between your daughter as an adult and her teachers to make that determination, and if that niche is where your daughter wants to thrive, trying to be supportive of her choices is what you likely should do, and your question indicates that it is also what you want to do.
The best way to do that may not involve you gauging her playing but let her navigate that minefield on her own and with her teachers.  At least as you are reasonably sure that her heart is in on this for her own good reasons rather than because she is trying to prove something to you.
Comment: Good answer.  Even the practice of well loved music can be unbearable to listen to, for example if the practicer is repeating a short passage a hundred times in rapid succession.
Answer: From my recent experience working from home, frequently in the same room as my wife, and inspired by the suggestion in the other answer to "find an arrangement where a good part of the time your daughter is practising, you just don't get to hear her," I suggest investing in a good pair of noise-canceling headphones and listening to something else while she is practicing.
Comment: Actually, noise-cancelling cans won't be that good for this sort of music - pitch leaps and sudden dynamic volume changes. Better would be in-ears with ear defenders on top. Or practise in the bathroom. (She might enjoy the enhanced sound anyway!).
Comment: O.k., so combine the two: n.c.cans and ear defenders - find someting which feels comfortable, and it's sorted.
Comment: Some noise-cancelling headphones are more effective than others. Better pick the right one for our need, rather than listening to something very loud to drown out the sound (which would damage our ears).
Comment: @Tim my experience suggests otherwise.  The noise cancellation doesn't cancel non-noise sounds completely, but it muffles the outside world enough that I can ignore it when I'm listening to something else through the headphones.
Answer: The existing answers ("Maybe don't listen?") make a good point, especially that practice is not performance. (I'm tempted to name-check https://en.wikipedia.org/wiki/Who_Cares_if_You_Listen .)
But to address the intent of your question, "How can anybody actually like this?" I can't claim that I sit down and listen to serialist music for enjoyment. But the closest I came was for a few weeks of my "20th century music theory" course in undergrad in which we had to actually learn the techniques, and submit a paper analyzing a Webern piece. I spent weeks staring at the score, circling things, and I discovered that what sounded abstract and arbitrary was in fact incredibly, meticulously, deliberate. I found patterns, inverted patterns, reversed patterns, chords that added up simultaneously to the pattern, patterns in the rhythms and even the meter, patterns handed off from one voice to another (or chased in canon). Even dynamics and articulations were mathematically calculated. To this day, when I go back and read the paper I wrote, I don't understand half of it. But in that moment, while I certainly didn't enjoy the piece, I understood it. To attempt to just sit down, let it wash over you, and appreciate the experience is perhaps comparable to listening to a recitation of a Shakespeare sonnet translated into Russian, without either analyzing the poem or understanding Russian.
It's a great irony that a genre born of a compulsion to totally control every aspect, and to pursue ultimate and absolute order, comes across sounding unordered and arbitrary. Of course, the practitioners of serialism believed that our facility to hear and appreciate the mathematical precision would evolve over time. It's telling that most, like Boulez, gave up on that dream and in fact turned to the opposite, indeterminism. Rather than giving the composer ultimate control, they set boundaries between the composer and the compositional process, like deriving content from the I Ching or putting tracing paper over star charts.
TLDR? Who says you have to enjoy everything? Even if your daughter does? But you can at least have a chance at understanding it, and for serialism that's the best kind of appreciation.
Comment: I wouldn't say that most of the people doing this kind of total serialism then went into indeterminism. Indeterminism was an approach that existed at the same time as represented by the "New York School" of John Cage, Morton Feldman, Earle Brown and Christian Wolff. The Europeans (Darmstadt School) did eventually embrace the use of chance ("alea") but it differed from the Americans in that it was strictly controlled chance (more like Mozart's dice music). Having said that, Stockhausen might be the exception as he was always embracing new ideas.
Answer: If you enjoy the Second Viennese School, but can't get into Boulez, I suggest you turn to the missing link in this timeline: Olivier Messiaen. He was the person who taught people like Boulez about the Second Viennese School, and his own experiments with Serialism (where the note pitches are serialized, as in Schoenberg's twelve-tone music) and Total Serialism (where all aspects of the music are serialized) had a strong influence on his pupils.
The interesting thing about Messiaen's music is that it developed through many stages, moving toward and away from (Total) Serialism at different times, and also incorporated many other techniques and influences. E.g. his use of transcribed bird song can be seen as a counterweight to the search for formalized composition techniques such as serialism, which was typical of much 20th century classical music; one is the sound of nature untouched by man, the other very much man-made and intellectual. (I suspect Messiaen turned to bird song whenever he had doubts about the validity of other composition techniques.)
The most Total Serialist of his composition is undoubtedly Mode de Valeurs et d'Intensités from the Quatre Etudes de Rythme for piano from 1949/50. This probably comes closest to what Boulez did in the 50's and 60's. But Messiaen moved away from this composition style after a few years, and serialism became only one of several techniques that he combined in his later works.
I would suggest exploring Messiaen's music chronologically, and also listening to Boulez's music of the same time when you reach the 50's. Maybe this will give you a way in, or at least a context in which to approach Boulez.
With a bit of luck, you may even get your daughter interested in exploring Messiaen and/or some of his other pupils besides Boulez.
Thème et Variations (1932) played by Janine Jansen and Itamar Golan
Louange à l'Immortalité de Jésus (1941) played by Gil Shaham and Myung-Whun Chung
Comment: Thanks. Husband and I were flabbergasted by your answer, LOL! We actually listen to Messiaen and have no issue with most of his pieces like *Turangalîla-Symphonie, Oiseaux exotiques, Des Canyons aux étoiles, Éclairs sur l'au-delà*. We never guessed Messiaen was "the missing link" to appreciating Ultra Serialism!!!


Derivative with respect a function of a functional with an inner integral

Question: I have to maximize the following functional, which depends on the function $
b(t),\ 0\leq t \leq T$
$Y=\int_0^T [f(\ b(t)\ )\ e^{\int_0^t b(v)^2 dv}]dt$
where b(t) can be supposed to be a "good" function (continuous, etc.).
I have thought to derive the functional with respect to $b(\cdot)$ (then null the equation and solve it), but I don't know how to deal with the inner integral. Any idea on how to do it? Do you have any good references on maximization of functionals?
Comment: What is the context? Did you use Grönwall's inequality?
Comment: The context is signal optimization... I didn't use Gronwall's inequality.
Answer: The substitution
$u(t) = \int_0^t b(v)^2 dv $
gives $b(t) = \sqrt{u'(t)}$ (let's suppose $b(t) \geq 0$). The functional becomes
$Y = \int_0^T f \left( \sqrt{u'(t)} \right ) e^{u(t)} dt$
and it is possible to use variational calculus.


Queue Scenario Help Getting Started

Question: Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{

private Node<E> head;
private Node<E> tail;
private int size;

public LinkedListQueue() {

}

public void enqueue(E element) {
    Node newNode = new Node(element, null);

    if (size == 0) {
        head = newNode;
    } else {
        tail.setNextNode(newNode);
    }

    tail = newNode;
    size++;
}

public E dequeue() {
    if (head != null) {
        E element = head.getElement();
        head = head.getNextNode();
        size--;
        if (size == 0) {
            tail = null;
        }
        return element;
    }
    return null;
}

public E first() {
    if (head != null) {
        return head.getElement();
    }
    return null;
}

public int getSize() {
    return size;
}

public void print() {
    if (head != null) {
        Node currentNode = head;
        do {
            System.out.println(currentNode.toString());
            currentNode = currentNode.getNextNode();
        } while (currentNode != null);
    }
    System.out.println();
}
}

Node Class
public class Node<E>{
private E element;
private Node<E> next;

public Node(E element, Node next) {
    this.element = element;
    this.next = next;
}

public void setNextNode(Node next) {
    this.next = next;
}

public Node<E> getNextNode() {
    return next;
}

public E getElement() {
    return element;
}

public String toString() {
    return element.toString();
}
}

Simulation Class
import java.util.Random;

public class Simulation {

private int arrivalRate;
//you'll need other instance variables

public Simulation(int arrivalRate, int maxNumQueues) {
    this.arrivalRate = arrivalRate;
}

public void runSimulation() {
    //this is an example for using getRandomNumPeople
    //you are going to remove this whole loop.
    for (int i = 0; i < 10; i++) {
        int numPeople = getRandomNumPeople(arrivalRate);
        System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
    }
}

//Don't change this method.
private static int getRandomNumPeople(double avg) {
    Random r = new Random();
    double L = Math.exp(-avg);
    int k = 0;
    double p = 1.0;
    do {
        p = p * r.nextDouble();
        k++;
    } while (p > L);
    return k - 1;
}

//Don't change the main method.
public static void main(String[] args) {
    Simulation s = new Simulation(18, 10);
    s.runSimulation();
}
}

Answer: It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
    this.arrivalRate = arrivalRate;
    // missing the handling of maxNumQueues
}

So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {

private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues

public Simulation(int arrivalRate, int maxNumQueues) {
    this.arrivalRate = arrivalRate;
    this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}

Comment: yes, i am just starting this and the summary for this assignment is very confusing as to what he wants

Queue Scenario Help Getting Started


Math for computer programming

Question: I'm a computer engineering student, and I'm trying to get a firm grasp of math before starting to program. I know that math is strictly related to programming, but I don't know what is the field of math most related to programming, for example, automata theory, compatibility theory, discrete math, type theory, category theory, lambda calculus etc can you guys tell me which math field is the most related to programming and computer science?
Thank you!
Comment: There is a big difference between computer programming and computer science. You can program a computer with minimal primary school level arithmetic and logic.
Comment: Spectral Graph Theory,Graph Theory,Number Theory, Analysis, Quantum Mechanics.
Comment: I used to research and develop algorithms, and graph theory was very helpful to know, and it helps to understand the object oriented paradigm a little too.
Answer: Discrete mathematics (set theory, logic, combinatorics, graph theory, etc.) is probably the branch most closely associated with computer science, although calculus (esp. optimization), numerical analysis, linear algebra, number theory, statistics, and information theory are also very important in theoretical CS. As far as programming goes, I would prioritize studying algorithms and try to get a solid grasp of the basics of discrete mathematics.
Here's a good starting point for you, the bible of math for CS.
Answer: It really depends heavily on what you are programming, I would even go as far as saying that programming in general does not really require any math skills beyond the overall understanding of the language and the notion of algorithm. However, to solve certain problems, maths skills will certainly help you

For designing algorithms and study their complexity in general, it is useful to be familiar with recursivity and induction, as well as recursive sequences. You will probably need to know how to classify the growth of sequence (the big O and small o notation)
For running scientific computations, like simulate a physical system or a biological ecosystem, you probably need a fair bit of analysis, know about ODE, PDE. Then the most important part is probably the results proving convergence of methods for solving them
There are also a lot of situation in which you want to apply linear algebra. I don't have examples on top of my head, but it is actually very common to compute the inverse of a matrix, or a base change. More advanced probably come up as well, even though a bit less often
If you do some data analysis, you definitely want a solid background in statistics
If you do machine learning, and especially neuron networks, I think you want to know at least the basics of multivariate geometry
If you want to experiment with functional programming, then category theory will be useful, especially if you try programming in Haskell. But it is by no means required.
If you want to understand the more theoretical aspects of computer science, and the general principles that make programming languages work in general, you probably need a bit of automata theory and formal languages, or even go till lambda-calculus and turing machines

As you can see, you don't really need to know any maths for programming, but as a programmer you will most certainly meet some maths, and even more so if you are a computer scientist in general. This list is certainly non exhaustive. My advice would be, if you want to have general knowledge in maths, to take a book of first year undergrad general and study from it, and doing the exercises. Everything you will find in there are what all mathematics rely on

Math for computer programming


What is the most dangerous sport in the Winter Olympics?

Question: The Winter Olympics, much more so than the Summer Olympics, includes lots of sports that seem dangerous.  Many of the sports involve incredible speed or jumps that are not found in the Summer games.  Of all the events in the Winter games, which is the most dangerous?
To be more specific, I'm wondering, of all the sports in the Winter Olympics, which sport has the highest rate of serious injuries or fatalities among participants; not necessarily only during the Olympics, but in general by people participating in the sport at a competitive level.
Comment: Yeah, agreed that "dangerous" is ambiguous. How would you want to quantify "dangerous?" # of injuries? # of deaths? Risk...even with "risk," it remains ambiguous.
Comment: @edmastermind29 Thanks, I've edited the question to be more specific.  Let me know if it still needs work.
Answer: It depends on what you mean by dangerous.
In Winter Olympic history it will happened twice that a Luge athlete died during the (practice) competion

Kazimierz Kay-Skrzypecki, - Luge - 1964, Innsbruck
Nodar Kumaritashvili, - Luge - 2010, Vancouver

other death in Winter Olympic competition were:

Ross Milne, – Downhill Skiing – 1964, Innsbruck
Nicolas Bochatay, – Speed Skiing – 1992, Albertville

Generally there were several tragical moment in winter sport (not during Olympic events) and I think alpine skying is where it happened most than other speciality (Ulrike Maier, Regine Cavagnoud, Nick Zoricic)
Another interesting article on injury in Olympic sports
Answer: The definition of what is the most dangerous Winter Olympic sport is dependent on how you quantify 'dangerous'. An obvious definition would be the number of fatalities. Whilst it is hard to find statistics for winter sports as a whole, the number of fatalities at the Winter Olympic games has totalled 4, with two of them occuring in the Luge:

Ross Milne (19), Australia – Downhill Skiing – 1964, Innsbruck - Ski collision in practice
Kazimierz Kay-Skrzypecki, Britain – Luge – 1964, Innsbruck - Luge crash in practice
Nicolas Bochatay (27), Switzerland – Speed Skiing (demonstration sport) – 1992, Albertville - Collided with a snow machine in practice.
Nodar Kumaritashvili (21), Georgia – Luge – 2010, Vancouver - Luge crash in practice.

Quantifying this is, as I say, difficult, but it is obvious that the higher the speed and the more acrobatic an event is then the higher the risk of injury.  Two good discussions are presented on these sites:

Danger zone: Which Winter Olympic sport is the least safe?
2014 Winter Olympics: The Definitive Ranking of Events, From Most Exciting to Barely Watchable
Comment: This is a good answer with an equally good assumption. The 2010 death of Nodar Kumaritashvili was the first in the sport of Luge [since 1975](http://sports.espn.go.com/olympics/winter/2010/luge/columns/story?id=4911753) according to the International Luge Federation.


LLVM branch instruction: if statement or loop in the source?

Question: For a conditional branch instruction in LLVM IR (as a terminator of a basic block), I would like to determine whether it corresponds to a loop or an if statement in the source code. Is there a way to analyze this?
Comment: There isn't necessarily a concept of source code when dealing with LLVM IR. Are you talking about e.g. IR generated by clang from C or C++ code?
Comment: Yes! That's what I meant (IR generated by clang from C).
Answer: Conceptually, a branch forward is an "if statement" and a branch backward is a loop. However this might be hidden behind some complexity, e.g. the frontend might create a conditional branch forward which leads to an unconditional branch backward, so overall a loop.
If you want to be sure, generate the IR with debug information, and then use that information - particularly, the line number - to understand what the original code was.


Importing and using overlay from jquery_plugin module

Question: I am trying (and failing) to use the jquery overlay plugin from the jquery_plugin module in Drupal 7.
I am using drupal_add_library() to add the plugin and drupal_add_js to add the code to generate the overlays.
The overlay trigger elements are area elements within a map.
Whenever I try and trigger the overlays, I get nothing - no errors or stacktraces or alerts, or messages in Firebug.
Here is the code - added directly into the page content.
drupal_add_library('jquery_plugin', 'overlay');
drupal_add_js('function($) {
    $(document).ready( function() {
        $(".overlayarea").overlay();
    });
}(jQuery); ','inline');

The map looks as the following:
<map name="globalmap">
    <area id="toronto" class="overlayarea" alt="Toronto" coords="94,195,6" shape="circle" rel="#tor_overlay" nohref />
    <area id="oxford" class="overlayarea" alt="Oxford" coords="576,147,6" shape="circle" rel="#oxf_overlay" nohref />
</map>

Answer: Actually this module seems to be abandoned. Using drupal_add_library() works only if the module used hook_library(). I wanted to check it in the repository of jquery_plugin, but these files aren't available. I don't know why.
If you want to use overlays, you can use directly the jQuery UI that is already included in Drupal 7.
Comment: If I remove the drupal_add_library call, Firebug informs me that overlay() is not a function (i.e. not included). Does that mean you have to include the script as suggested by @czervik?
Answer: I'm not familiar with using the jQuery plugin module; personally I simply add whatever I need to my theme.info file.

    scripts[] = js/jquery-tools1.42/jquery.tools.min.js

Then overlays are available sitewide.
Comment: I have added other js files this way with no problems. If this is the answer, what is the point of the plugin module?
Comment: The plugin module lets modules reuse a jquery plugin. If you want the overlay to be a theme-independent feature, it is very useful. Try the Libraries module for D7.
Answer: I fixed this by using the Colorbox module and the Imagemap plugin for TinyMCE. Adding class="colorbox' to the map area allowed me to use an overlay for that area.


SMO 2013 Junior First Round Q35.

Question: In a competition that i have recently taken part in, one of this questions popped out:
$2^{29}$ has nine distinct digits. Find the digit that is not in the sequence.
My answer will be placed as a 'Answer-your-question'.
However, my main question is: are there other methods?
Answer: Most people did the same as me:
Since closed to nothing would do. There was only one thing to do. SMACK the question with plain and good-ol' Brute-force.
From that, we now know that the answer is 4.

SMO 2013 Junior First Round Q35.


Not able to implement Native Video ads through Manual Integration in android using Mopub

Question: As the Documentation of Mopub say's here ,integrated the Native ads and followed by Native Video ads.
After integrating the code the ad request response is calling the callback method onNativeFail()
with some of the response
Below code is related to the workflow and logcat message
public class MainActivity extends Activity {
private MoPubView moPubView;
//private MoPubInterstitial mInterstitial;
private MoPubNative moPubNative;
private MoPubNativeNetworkListener moPubNativeNetworkListener;
private NativeAd.MoPubNativeEventListener moPubNativeEventListener;
AdapterHelper adapterHelper;
private NativeFullScreenVideoView nativeFullScreenVideoView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    moPubNativeNetworkListener = new MoPubNativeNetworkListener() {
        @Override
        public void onNativeLoad(NativeAd nativeAd) {
            Log.d("MoPub", "Native ad has loaded.");

        }

        @Override
        public void onNativeFail(NativeErrorCode errorCode) {
            Log.d("MoPub", "Native ad failed to load with error: " + errorCode.toString());
        }
    };

    moPubNativeEventListener = new NativeAd.MoPubNativeEventListener() {
        @Override
        public void onImpression(View view) {
            Log.d("MoPub", "Native ad recorded an impression.");
            // Impress is recorded - do what is needed AFTER the ad is visibly shown here.
        }

        @Override
        public void onClick(View view) {
            Log.d("MoPub", "Native ad recorded a click.");
            // Click tracking.
        }
    };

    moPubNative = new MoPubNative(this, "02a2d288d2674ad09f3241d46a44356e ", moPubNativeNetworkListener);

    ViewBinder viewBinder = new ViewBinder.Builder(R.layout.native_ad_list_item)
            .mainImageId(R.id.native_main_image)
            .iconImageId(R.id.native_icon_image)
            .titleId(R.id.native_title)
            .textId(R.id.native_text)
            .privacyInformationIconImageId(R.id.native_privacy_information_icon_image)
            .build();

    MediaViewBinder mediaViewBinder = new MediaViewBinder.Builder(R.layout.native_video_ad_layout)
            .mediaLayoutId(R.id.native_ad_video_view)
            .iconImageId(R.id.native_ad_icon_image)
            .titleId(R.id.native_ad_title)
            .textId(R.id.native_ad_text)
            .build();

    MoPubVideoNativeAdRenderer moPubVideoNativeAdRenderer = new MoPubVideoNativeAdRenderer(mediaViewBinder);
    moPubNative.registerAdRenderer(moPubVideoNativeAdRenderer);

    MoPubStaticNativeAdRenderer moPubStaticNativeAdRenderer = new MoPubStaticNativeAdRenderer(viewBinder);
    moPubNative.registerAdRenderer(moPubStaticNativeAdRenderer);

    EnumSet<RequestParameters.NativeAdAsset> desiredAssets = EnumSet.of(
            RequestParameters.NativeAdAsset.TITLE,
            RequestParameters.NativeAdAsset.TEXT,
            RequestParameters.NativeAdAsset.CALL_TO_ACTION_TEXT,
            RequestParameters.NativeAdAsset.MAIN_IMAGE,
            RequestParameters.NativeAdAsset.ICON_IMAGE,
            RequestParameters.NativeAdAsset.STAR_RATING
    );

    RequestParameters mRequestParameters = new RequestParameters.Builder()
            .desiredAssets(desiredAssets)
            .build();

    moPubNative.makeRequest();

}

}
After running this code, the ad is not getting loaded and the response of my code is below
06-06 17:01:41.797 24421-24421/? I/Ads: Webview loading for native ads.
06-06 17:01:41.911 24421-24421/? I/Ads: Javascript has loaded for native ads.
06-06 17:02:18.623 24421-24421/? I/Ads: Webview loading for native ads.
06-06 17:02:18.954 24421-24421/? I/Ads: Javascript has loaded for native ads.
06-06 17:02:51.796 13278-13278/com.fabgrad.students.android D/MoPub: Native ad request failed.
                                                                 com.mopub.network.MoPubNetworkError: No ads found for ad unit.
                                                                     at com.mopub.network.AdRequest.parseNetworkResponse(AdRequest.java:180)
                                                                     at com.mopub.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:132)
                                                                     at com.mopub.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
06-06 17:02:51.800 13278-13278/com.fabgrad.students.android D/MoPub: Native ad failed to load with error: Server returned empty response.

Answer: As per their blog, No ads found will come for following scenarios:
These errors indicate that there was no fill for your ad unit.
No ad network will have fill 100% of the time, so seeing this log is normal. New apps and apps with very low volume tend to experience lower fill rates. Contact your ad network representative if you have any concerns related to a particular network's fill.
If you are consistently seeing no fill, review your ad network placement details in the Networks tab of the MoPub UI, as well as your settings in the Network's UI.
You won't be able to show ads from Certified Ad Networks if you forgot to include the network SDK or adapter files. The Couldn't locate or instantiate custom event and Unable to find Native Network or Custom Event adapter log messages are indicators that the network SDK or adapter file is missing, renamed, or in the wrong location.
Review our Integrating Third-Party Ad Networks documentation to resolve this.
Link for reference.


Throwing Dice N Times

Question: You Throw Two Dice.  One of the possible many outcomes that may occur is that you get a six on each die (this outcome is called a double six).  How many times must you throw the two dice in order for the probability of getting a double six (on one of your throws) to be at least .50?
I completed this problem by setting up the equation .5 = (1/6)(1/6)N
N= 18 times.  Is this correct?  Can someone please provide me with the proper equation.  Thanks so much.
Comment: Hint: If you throw $n$ times then what is the probability that **no** double six was thrown?
Comment: Further hint: the [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) should be useful here.  $Pr(X=k)=\binom{n}{k}p^k(1-p)^{n-k}$
Comment: So is it (35/36)^N = .5?  Do I need to solve using logs?
Comment: Yes (or just substitute some values for positive integer $n$), and actually you are not solving an equation but an inequality: $1-(\frac{35}{36})^n\geq0.5$ for positive integer $n$.
Comment: So is the answer 24.6 times or 25 times?
Comment: 24.6 times is not possible. 25 is correct.
Comment: I solved for (35/36)^N = .5 to get 25 times.  If you solve for 1-(35/36)^N = .5 don't you 70 times?
Answer: The probability of getting a double 6 on any throw is $\frac {1}{36}$
Your probability of getting not getting any 1 double 6s on N throws is $(1-\frac 1{36})^N$
Solve for N such that
$(1-\frac 1{36})^N < 0.5$
$N \log (\frac {35}{36}) < \log {\frac 12}\\
N > \frac {\log 2}{\log 36-\log 35}$
Answer: Ask yourself the following:
$p(double \space six)=$
That means $p(no \space double \space six)=$
Chaining this: $p(no \space double \space six \space in \space n \space tries)=$
Again negating: $p(at \space least \space one \space double \space six \space in \space n \space tries)=$
Now just solve for what $n$ the last probability is $>0.5$
I can't quite tell what you mean by your equation...
Comment: The return key just doesn't do anything if pressed only once.  His attempt was to set $0.5=\frac{1}{36}N$ and thinks this implies $N=18$

Throwing Dice N Times


Borel-Cantelli lemma: non-negative iid random variables

Question: I came across a claim in a paper on branching processes which says that the following is an immediate consequence of the B-C lemmas:

Let $X, X_1, X_2, \ldots$ be nonnegative iid random variables. Then $\limsup_{n \to \infty} X_n/n = 0$ if $EX<\infty$, and $\limsup_{n \to \infty} X_n/n = \infty$ if $EX=\infty$.

So to apply the BC lemmas to these, I want to essentially show that
$$(1) \; \textrm{If } EX<\infty, \textrm{ then } P(\limsup \{X_n/n > \epsilon\}) = 0 \quad \forall \epsilon>0$$
$$(2) \; \textrm{If } EX=\infty, \textrm{ then } P(\limsup \{X_n/n > \delta\}) = 1 \quad \forall \delta>0$$
But I keep getting stuck. For example if I want to apply the first BC lemma to (1), then using Markov's inequality only gives $P(X_n > n\epsilon) < EX/n\epsilon$, which isn't summable. Am I missing something right under my nose?
Comment: what is $X$ in $EX < \infty$?
Comment: @Calculon $X$ is a generic random variable with the same distribution as the $X_i$, as stated in the post.
Comment: The second part is proved here: http://math.stackexchange.com/q/1332735/ (However, the proof doesn't use BC lemma, but SLLN).
Answer: (a): Say $\epsilon>0$. Let $E_n$ be the event $X_n/n > \epsilon$. Then $$\sum P(E_n)=\sum P(X_1>n\epsilon)<\infty$$because $EX_1<\infty$ (standard lemma). So BC says $$P(\limsup X_n/n>\epsilon)=P(E_n i.o.)=0.$$
(b): Same as (a).
Maybe what you're missing is that "standard lemma" referred to above?
Lemma. If $X\ge0$ then $\sum_{n=1}^\infty P(X>n)\le EX$.
Proof: (Notation inconsistent with the notation above.) Let $X_n=\min(X,n)$. Then $X_n$ increases to $X$ and $X_0=0$, so $EX=\sum_{n=0}^\infty E(X_{n+1}-X_n)$. But $X_{n+1}-X_n\ge0$ and $X_{n+1}-X_n=1$ on $E_n=\{X>n\}$, so $E(X_{n+1}-X_n)\ge P(E_n)$. QED.
Of course you need a slightly different version of the lemma for part (b).
Answer: Essentially what you need to show is that

If $X$ is a non-negative random variable, then $EX < \infty$ iff $\sum_n^{\infty} P(X > n\epsilon) < \infty$ for every $\epsilon > 0$.

The direct part is sufficient for part (a) obviously, but you will also want to establish the converse direction for part (b) because you will need to apply the 2nd BC lemma and show that, if $EX = \infty$ then $\sum P(X_n > n\epsilon) = \infty$ no matter how large of a $\epsilon>0$ you chose.
For the first direction $(\Rightarrow)$, note that for any $\epsilon>0$,
$$\sum_{n=1}^{\infty} \epsilon \cdot \mathbb{1}_{(X>n\epsilon)} < X$$
If you view the LHS as the limit of a sequence of partial sums then the MCT gives
$$\epsilon \sum_{n=1}^{\infty} P(X>n\epsilon) < EX$$
For the opposite direction $(\Leftarrow)$ just note that
$$\sum_{n=1}^{\infty} \mathbb{1}_{(X>n-1)} > X$$
Take expectations and limits as above and you will get
$$\sum_{n=1}^{\infty} P(X>n-1) > EX$$
And apply the assumption with $\epsilon=1$.


Why can't I implement a default interface method in a class inheriting an abstract class that inherits that interface?

Question: I have an interface and an abstract class inheriting this interface.
public interface ISomeInterface
{
    int Method()
    {
        return 1;
    }
}

public abstract class SomeAbstractClass : ISomeInterface {}

Now I want to implement a class inhereting SomeAbstractClass that will also implement int Method().
public class SomeClass : SomeAbstractClass
{
    public int Method()
    {
        return 2;
    }
}

However when calling Method() on a casted SomeClass object to ISomeInterface it'll display 1.
ISomeInterface someClass = new SomeClass();
Console.WriteLine($"{someClass.Method()}"); // displays 1

But if I add interface to SomeClass
public class SomeClass : SomeAbstractClass, ISomeInterface
{
    public int Method()
    {
        return 2;
    }
}

It'll display 2.
Why is that the case? Is there any way to declare/implement Method() by just inhereting from SomeAbstractClass but without the need to write , ISomeInterface too?
I also don't want to modify the SomeAbstractClass if possible.
I tried searching for the explanation online, but it's difficult to explain this problem in a simple sentence. I've tried to read more about default interface methods, but learned nothing meaningful.
Comment: @SimonC: Did you try compiling it with a modern C# compiler? See https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/mixins-with-default-interface-methods for example.
Comment: You can't implement a method in an interface. Only in [abstract] classes. That code wouldn't compile
Answer: As you have noticed, the Method declared in SomeClass does not implement ISomeInterface.Method. You cannot implement ISomeInterface.Method in SomeClass, because SomeAbstractClass has already fully implemented ISomeInterface.
By not declaring any members matching the signature of ISomeInterface.Method, SomeAbstractClass fully implements ISomeInterface by "opting in" for the default implementation of Method.
This is consistent with how abstract classes usually work - if Method didn't have a default implementation, an empty SomeAbstractClass would have caused a compiler error. If you want SomeAbstractClass to not implement Method, and let its concrete subclasses do the job instead, you need to add the following to SomeAbstractClass (regardless of whether Method has a default implementation):
public abstract int Method();

When Method does have a default implementation, this is called reabstraction.
See also this question, which is about how you still have to declare the member in the abstract class, in order for it to implement a non-default interface member.
Note that by adding the abstract method to SomeAbstractClass, you would now also be able to call Method on things of type SomeAbstractClass, whereas you couldn't previously.

The situation is kind of like this:
// not actually how default interface members are implemented under the hood,
// just for illustration purposes only
public interface ISomeInterface
{
    int Method();
}

public abstract class SomeAbstractClass : ISomeInterface {

    public int Method() => 1;
}

public class SomeClass : SomeAbstractClass
{
    public int Method() => 2; // this method obviously does not implement ISomeInterface.Method!
}


insert Data Into MySQL Database Using Php PDO Probloem

Question: I am trying to insert to my database using PDO but I have a problem with my code:

( ! ) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user`, `pass`) VALUES (?,?)' at line 1' in C:\wamp64\www\Pd\sql.php on line 16
( ! ) PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user`, `pass`) VALUES (?,?)' at line 1 in C:\wamp64\00\00\sql.php on line 16

My code:
<?php
$dbname ="snabel_db";
$dbhost ="localhost";
$dbuser ="root";
$dbpass ="";
$db = new PDO('mysql:dbname='.$dbname.';host='.$dbhost.';charset=utf8', ''.$dbuser.'', ''.$dbpass.'') or die();

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['add'])){

    $user2 = $_POST['user'];
    $pass2 = $_POST['pass'];
    $sql ="INSERT INTO `user`('user`, `pass`) VALUES (:user1,:pass1)";
    $sqlreuslt = $db->prepare($sql);
    $pdoexec = $sqlreuslt->execute(array(":user1"=>$user2,":pass1"=>$pass2));
    if($pdoexec){
        echo 'DOne';
    }else{
        echo 'error';
    }
}
?>
<!DOCTYPE html>

    <title>Sql Test</title>

<form method="post" action="sql.php">
    Username<input type="text" name="user">

    Password<input type="password" name="pass">
    <input type="submit" name="add">
</form>

Comment: firstly I'd suggest changing your connection to `$db = new PDO('mysql:dbname='.$dbname.';host='.$dbhost.';charset=utf8', $dbuser, $dbpass ) or die();`
Answer: The PDO constructor looked to be incorrect - a strange use of single quotes when, for the user and password, they were not needed as they were assigned as variables.
You might also like to broaden the isset condition to include the other POST variables that you expect to be present and also test for a successfully prepared statement too?
Common thought these days is that passwords should be stored as a hash rather than as plain text - to that end password_hash and password_verify should be on interest.
<?php
    /* sql.php */

    $dbname ="snabel_db";
    $dbhost ="localhost";
    $dbuser ="root";
    $dbpass ="";
    $db = new PDO('mysql:dbname='.$dbname.';host='.$dbhost.';charset=utf8', $dbuser, $dbpass ) or die();

    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if( isset( $_POST['add'],$_POST['user'],$_POST['pass'] ) ){
        $user2 = $_POST['user'];
        $pass2 = $_POST['pass'];

        $sql ="insert into `user` ( `user`, `pass` ) values ( :user1, :pass1 )";
        $stmt = $db->prepare( $sql );

        if( $stmt ){

            $pdoexec = $stmt->execute( array( ":user1" => $user2, ":pass1" =>$pass2 ) );

            if( $pdoexec ){
                echo 'Done';
            }else{
                echo 'error';
            }
        } else {
            echo "statement error";
        }
    }
?>

<!DOCTYPE html>

    <title>Sql Test</title>

<form method="post" action="sql.php">
    Username<input type="text" name="user">

    Password<input type="password" name="pass">
    <input type="submit" name="add">
</form>

Comment: ( ! ) Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 't7-' for column 'user' at row 1' in C:\wamp64\www\Pd\sql.php on line 22
( ! ) PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 't7-' for column 'user' at row 1 in C:\wamp64\www\Pd\sql.php on line 22
Answer: Wrong quote here
"INSERT INTO `user`('user`, `pass`)

You need
"INSERT INTO `user`(`user`, `pass`)


Create javascript array which have the same structure with php array

Question: In the sever side i have an array with structure like that:
array ('_1489378560544_544' => array (
                                     'customer_group_id' => '0',
                                     'permission_id' => 'disable_products_price',),
       '_1489740032764_764' => array (
                                     'customer_group_id' => '',
                                     'permission_id' => '',),)

So now in the client side i want to create an javascript array with the same structure to server side. Is there any possible way to do that?
So after i got all data separately how can i organize my array look like this
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]

Here is my javascript get data function:
 $('#category_permission > tbody > tr').each(function() {
                var id = $(this).attr("id");
                var customer_group_id = $(this).children('td:first').children('select:first').val();
                var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
            });

Thanks for your help.
Comment: For sure. Its quite simple. But we're not here to code for you. http://stackoverflow.com/help/how-to-ask .. show us what you've tried so far and we'll help you find your mistakes.
Answer: You can use json_encode  to convert your PHP array to a JSON string and use JSON.parse() to obtain the equivalent Javascript object. Take a look here: https://www.w3schools.com/js/js_json.asp
Answer: Something like this :
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
Comment: Hi Avihay. Your answer is exactly what i'm looking for. So after i got all data separately how can i organize my array like yours. Here is my get data function.
$('#category_permission > tbody > tr').each(function() {
                    var id = $(this).attr("id");
                    var customer_group_id = $(this).children('td:first').children('select:first').val();
                    var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
                });
Comment: I cant understand what you are trying to do ?
Comment: My purpose is getting data from a table and then organize it like your answer. Obove is my javascript get data function form a table.
Comment: So define a variable like my example and build him with your variables.
Answer: in your php view file
jsStr = '<?php echo json_encode($array)?>'

jsObj = JSON.parse(jsStr);

console.log(jsObj.keyname);

like that all keys can be accessed to get the value. javascript don't support alphanumerical keys for array.
Answer from @Mistalis should help.
Comment: Hi Ervishalporwal. Mistalis's answer is in reverse order to what I want to do. My purpose is getting data from a table and then organize it in the form like @Avihay's answer
Comment: Do you want to print it like @Aviha's answer?


Color of the sprint jersey in Tour de Suisse?

Question: Tour de Suisse has two separate jerseys for sprints competition (based only on points from intermediate sprints) and points competition (where the points obtained from placement in stages are included; I am not sure whether they count here the intermediate sprints, too.)
The current revision of the Wikipedia article White jersey says that:

The Tour de Suisse awards a white jersey to a somewhat unique competition, the Sprints classification,[5] which awards placings not on stage finishes but strictly in intermediate sprints.

The link given there shows the leader of the sprints classification in 2008 wearing the white jersey.
Seasons 2005-2013 have individual articles on Wikipedia - the links can be found in the article about Tour de Suisee. When I checked these articles I have seen that:

In 2008, the color is shown as white.
In 2007, sprint classification is mentioned, but no information about the color of the jersey is in that article.
In 2012 the sprint classification is not mentioned at all, so it was probably not awarded.
Wikipedia articles on seasons 2005, 2006, 2009, 2010, 2011 and 2013 show the color of the sprint jersey as blue.

Of course, there might be mistakes in Wikipedia articles and Wikipedia gives no information about sprint competition before 2005.
I would like to know:

Was the year 2008 the only year, when the color of the jersey for the sprints competition was white?
When was the sprint classification (separate from the point classification) introduced in Tour de Suisse for the first time?
Answer: I can answer your first question. Your second question would be more difficult to track down.
In the Tour de Suisse (and in fact, many other stage races as well), the jerseys' colors simply change from year to year. Even the rules change quite often. In 2012, for instance, there was no intermediate sprints jersey. Instead, there was a red jersey for the best Swiss rider in the general classification. Often, these color changes are caused by changes in sponsors. This is quite prominent in the Tour of Spain, for instance: even the general classification's leader jersey (which would typically be seen as a very traditional prize) has changed numerous times throughout the years.
2008 was not the only year when the sprints jersey was white. The same color was used in 2007. After that, the blue color has been used fairly consistently, but it may be up for change again next year.
Answer: The first reference I can find for the separate sprint classification is from the year 2000.
See Wikipedia's article (in Italian) on this subject: Tour de Suisse 2000.
There were 2 different sprint classifications, but I can't tell which was the purpose of that. In 2001 there were even 3 different sprint classifications. My bet is that it also has to do with sponsorships, like the colours of the jerseys.