How to turn each chord in a progression into separate scales?

Question: I was jamming with some jazz guys yet I'm not so good in jazz so I made a bunch of mistakes. One of the things they told me is is how inside of a chord progression, you then spread each chord to its associated scale. So if you have a four chord progression, you could potentially have four different scales. And I never came across that before. One guy even told me it's "spicy" to flatten certain notes of each scale as well.
So I was wondering what the theory is in regards to this. How do you turn each chord into its scale. For example, let's say I have the I-IV-V chord do I then play/pick notes from the associated major scale of each one of these. And then for ii,iii,vi you play the associated minor scales? Are there rules then as  what to flatten? Or other rules in regards to certain chords, like dominant seventh chords, or other chord types how do you turn those into scales, do you just randomly pick what scale contains those notes or is it more to it? And when you have the a new sub-scale can you then turn to new chords inside of it.
I tagged this as jazz, but I'd like to apply this theory to other genres as well. I mainly play movie soundtracks, video game music (hence my interest in jazz), pop, new classical, stuff like that.
Comment: @Pyromonk you have alot of important things to say pls consider making it an answer!
Comment: no. Most of the time, I only do it for solos or to add some "spice" to a certain phrase. There is no real reason to do it all the time, unless you are playing free jazz. Playing a corresponding scale over a chord, as far as I see it, is a way of "distancing" a certain musical phrase from the main key and adding some variation to it. I am playing tenor saxophone, so your mileage may vary. As a piano player you might be expected to add more variety, depending on the style of jazz you play.
Comment: As far as my personal experience goes, jazz, especially modern jazz, very rarely uses natural major and minor scales. The answer to your question largely depends on what type of jazz you're playing... Swing? Be-bop? Free jazz? I am mostly playing "old" jazz, and the most common scales for me are harmonic minor, be-bop major (ascending), be-bop dominant (descending), blues hexatonic major and blues hexatonic minor. Given that jazz largely relies on maj7 chords, you can take the chords for your piece and see how they fit into the aforementioned scales.
Comment: @Pyromonk but are you always cycling through those scales as they relate to the chords? like in a chord progression do you usually use multiple scales?
Comment: To expand on my comment a little bit, playing over scales that are related to a chord is basically a way of adding chromaticism to a musical composition. It is commonly used in jazz and modern classical music. So if you are not playing a rhythm-section instrument, and you know what key and chord the rhythm section plays in a given bar, you can use your knowledge of scales to add some additional notes. I very rarely see more than 2 chromaticisms per bar in the jazz music that I play. Naturally, it requires some understanding of pitch and a good command of chords to pull off if you're jamming.
Comment: What song or progression was it? What mistakes did you make?
Comment: It is quite easy to improvise in a jazz jamming group.

What you need is some riffs and licks, that fit to many chord progressions and to many chords, and if a note doesn't fit then the neighbor note will brobably fit and it was a chromatic approach. If the sound was really weired you just have to repeat the motive once or more times, to make the audience believe it was ment to be! ;)
Answer: Modern classical music and jazz heavily rely on chromaticisms (notes outside of a piece's main key and scale). Playing a scale different to the piece's/section's main scale on top of a chord played by the rhythm section is one of the ways to add chromaticisms to a musical composition. These days, I mostly play "old-school" jazz, and I rarely see more than 2 chromaticisms per bar. When there's more, it's usually a chromatic progression from one note to another or a trill.
When composing or playing music, I mostly employ this technique for solo phrases, to add more "spice" to a phrase or to emphasise a transition from one chord to another (similar to drum breaks, which usually signify a change of chords or moving from one section of a piece to another).
The scales you employ and how often you introduce chromaticisms depends on the style that you play and your instrument and its role within the ensemble. In most musical genres, the rhythm section is not expected to move outside of the main key and scale for the piece/section. For example, the bass is expected to outline the tonic and the dominant of the chord being played. Piano in some styles of jazz is expected to be very "inventive" and play maj7 chords and their related scales/modes.
Free jazz and some styles of modern classical music depend on chromaticisms, and this is where I would personally expect every instrument (sometimes even the rhythm section) to play unrelated scales over a chord, or change key and/or signature every bar/phrase, or some unconventional logic to be used for musical progression. Probably, one of the most famous jazz composition progressions is "Coltrane Changes".
Usually, when it comes to jamming, you are either given a note sheet that outlines the chords per bar or the other musicians tell you what conventional progression you are going to use (12-bar blues being one), what key the rhythm section will be playing in, and what scale they are going to use. If you practise your scales every day, it should not be too difficult to take a look at the note sheet and find out what chromaticisms you can add to any given bar. If you have your personal printout, you can even add them to it in advance. I do not have perfect pitch or an eidetic memory, so that's what I normally do.
I started out as a percussionist (drums, kettle drums, xylophone) in a folk orchestra for kids and teenagers, playing in some metal, grindcore and mathcore bands and composing videogame music on the side, so I understand the difficulties you are facing. Jazz can become very complex, but most of the time it's important to know the chords per bar and the scales commonly utilised in jazz (harmonic minor, be-bop major (ascending), be-bop dominant (descending), blues hexatonic major and blues hexatonic minor). You might even add whole-half/half-whole diminished scales to your phrases, to add more of a "metal" feel to them.
To give you a more concrete example, the piece might be in, say, A blues hexatonic minor, and the rhythm section plays a min7 chord in the first bar (A-C-E-G). You decide to impress the audience and play outside of the piece's main scale. Your pick that day is the half-whole diminished scale in A. You quickly remember that its notes are A-B♭-C-C#-D#-E-F#-G. As you know, the half-whole diminished scale has the min7 chord as well. But you can add a few "blue" notes (chromaticisms) to the rhythm section's chord and play A-C#-D#, for example. That way, all of you will start on the same tonic (A). Your sound will be a bit "dissonant", but the listeners will still perceive it as "viable", because it is still within the main key of the piece and the root of the chord (A) and within the scale you have picked for your little "solo" (A half-whole diminished).
I would also like to add that I prefer to be consistent with scales that I "go away" to within a musical piece and not overuse this technique. If you jump between scales all the time, the average listener won't be able to follow. But if the rhythm section plays one scale, and you only ever change to another one, there will still be some audial consistency to what you're playing. Naturally, this rule does not really apply to free jazz or neo-classical music that is fully or almost fully chromatic in nature.
Hopefully, this makes sense.
Comment: It's just that I tell students that eventually, 'any note in any key, can be played anywhere in any tune, once you know what you're doing. Just have to know the rules to be able to break them'. Basically, any note can be and is used anywhere in jazz, that's one of the reasons I love playing it. Making it all work, despite the 'rules' we maybe ought to abide by!
Comment: Not at all. The basic use of basic scale notes against certain chords is a tried and tested method, which we all fall back on, probably the first choice with a new number. it's safe and (almost) foolproof. A good start point.
Comment: Almost worth just saying ' in this piece, in that key, these two notes are the only ones that don't work too well'. I'm sort of joking..!
Comment: @Tim, there's truth to every joke. What would you personally change or add within my answer?
Comment: @Tim, I completely agree! I was trying to lay out some basic ideas for foreyez to explore, since he has little to no experience with jazz. I think it's best to start out with the basics, which, in this case, might be learning some of the history and ideology behind jazz. I am in no way a professional teacher or musician. Hopefully, my attempt at "simplifying" things was not too crude.
Answer: One way to "turn each chord into [its] scale" is the chord-scale system. Be aware that it is mainly jazz-oriented and that it will often offer some pretty disgusting scales for any given chord (the first Wikipedia example offers the C whole tone scale for a chord consisting of C, E, G♯, and B♭).
Comment: This is the concise answer. Another downside to the chord/scale system is _some_ people won't recognize simple progressions like `ii V I` as simple diatonic patterns. Some seem to insist jazz is all chromatic without recognizing obvious diatonic patterns.
Comment: To get this as the "correct" answer from an internet search... I would emphasize that it is just one way. To me the chord-scale system seems like a shortcut to being able to play something that cannot be said to sound completely _wrong_, but without having to understand functional harmony and chord roles very deeply. In the chord-scale system, how do you even decide which fitting scale to select, if you don't have a sense and taste of what you want to imply in terms of functional harmony? Just select something randomly? :)
Answer: Another name for improvisation is vocabulary.  Knowing theory will help you discover your vocabulary to use in improvisation.  The second best way to learn to improvise is to listen to players you like and imitate them.
One of the first lessons I prescribe a student wishing to explore improvisation are upper/lower neighbors and passing tones.
A chord is typically made up of, for example, the 1, 3, and 5 of a scale. Then explore the half step lower or lower neighbor of each chord tone.

Then explore the upper neighbor or half step higher.

Then employ passing tones such as going from C, C# to the D.  Put them all together to create "rambling" lines:

Then you can employ superimposed chords which are actually modal.  For instance, if you are playing a G7 chord, you can play an A or Db chord over it:

Try to refrain from playing "licks." Learn your musical alphabet.  Playing licks is like being able to speak but not read. Don't make the mistakes I made.
Answer: The chord-scale system is pretty standard in jazz improvisation. Gary Burton teaches chord-scale in his Berklee College of Music class on jazz improv, so your fellow musicians are in good company in advocating its use.
Burton starts off with the assumption that you know the major and minor scales, and then clarifies the modes of each scale. From there, the rough concept is as follows, assuming the key is C major:

C major chord - play the C ionian/major scale
D minor chord - play the D dorian scale
E minor chord - play the E phrygian scale
F major chord - play the F lydian scale
G major chord - play the G mixolydian scale
A minor chord - play the A aeolian/minor scale
B diminished chord - play the B locrian scale

At this point, you're probably thinking "why not just play C major for all of those?" You could do that, but it helps to get your mind thinking along the lines of playing the different scales for each chord because you can't get very far in jazz without seeing a ton of non-diatonic chords, and you want to practice understanding which scale to play over which chord. For example, over any diminished chord, one reasonable option is to play a locrian scale with a keynote the same as the root of the chord.
There are also several other scales that work better or differently over various chords, such as the bebop dominant scale (I think Burton calls this just a "dominant scale" but for many that refers to a different scale) and the augmented scale. The bebop dominant scale might be played over any dominant seventh chord.
One more important complication in chord scales is that you can't ignore the normal melody line of a jazz piece when picking your chord scales. Well, you can ignore it, but then your solo might sound odd. When the melody note is not a chord tone, it's best to take it into account when picking your chord scale. For a super simple example, if the chord is a C major chord and there's a Bb in the melody at the same time, it's better to play a C bebop dominant scale or C mixolydian instead of C major.
I believe there's a free version of Burton's class on jazz improv available on Coursera, and I highly recommend it. Either way, you can learn to determine chord scales by starting slowly and analyzing some jazz lead sheets and writing in the scale that you would use over each chord. Keep in mind that chord changes don't always require scale changes. After marking up a lead sheet, practice soloing with it by improvising based on the scales you wrote down. Keep doing that until the process for picking scales becomes automatic.
Comment: @foreyez The reason there is that the idea of the example is that the melody would be in C major and therefore would not have a Bb in it, and a D minor scale has a Bb.
Comment: actually I was thinking why not play the D minor scale for the D minor chord for example
Answer: I don't understand this "one scale per chord" concept at all. You should imagine your own different chords on top of the backing instruments, and the fewer notes they play, the more freedom you have. The chords might imply scales, yes, but you don't have to think about the scale as your first priority. Think about chords, and let the scale question resolve itself when needed, if needed.
Even if the progression only has one chord in it, you overlay different stuff on it, to give that one chord different interpretations. If it's a C major, you can imagine the C in any number of roles. Play an Fm on it ... what scales or harmonic contexts does that combination remind you of? How about a Db major? D major? Bb minor? E major? How about a sequence of major chords: C - A - Gb - Eb - C? Does your "harmonic situational awareness" change if you don't play them as chords, but arpeggiate them?
It doesn't have to be anything complicated. If the backing chord progression does a I-IV transition going from C to F, think of some chord tricks you could do to support that transition. Think of it as V-I in F. Or ii-V-I in F. Play a C7 on the C. Play a C9 on the C. Play Gm - C9 - Gb9 ... feels nice, right before going to the F, right?
What I'm saying is, instead of having to jump directly to complete scales from the given chords, another way to look at the problem is, you're re-arranging the song with new, more jazzed-up chords. And then you reveal bits and pieces of your improvised arrangement as you go.
Comment: I like to think about it as sub-scales, like subdirectories in a file system.
Comment: @foreyez: think about what? Does my answer make any sense to you - would it enable you to do something in a soloing situation?
Answer: I do like the selected answer, but judging by the question, it might be more than you need at this point.
What you really should be doing is listening to the kind of music you want to play. Figure out what they are doing in solos that you like. I'm suprised no one suggested this. Maybe when you're jamming with your more experienced friends, get them to show you what they are doing.
For the type of music you are apparently playing (I-IV-V etc.), you probably don't need to know all that much. Solos in basic progressions tend to be fairly diatonic, meaning basically in the same key. Focus more on rhythmically strong phrases and developing ideas. The selected answer mentioned Gary Burton, this is what he taught in improv. classes.
So, come up with a short motif, two, three or four notes, and "develop" it throughout your solo. (if you don't know what this means, look up "developing motifs"). Also, a lot of solos in pop music focus on the chord tones, so you don't have to get too crazy with scales.
If you want to "spice it up" a little with passing tones, when in a major key, you can mix in the b3 and the #4, (in C, that would be Eb and F#), which imply a minor blues key. You can really play chromatic passing tones anywhere, usually these are on weak beats or off the beat, but you have to use your ear to figure out what works for you.
I don't know that you are going to pick up everything there is to know about music theory from a post, people study this stuff for years. If you are really interested, you could always take an improvisation course online from Berklee.


Is it possible to force a linux install to continue?

Question: I'm PXE booting a linux distro that I'd like to contain a list of packages. I have these packages listed in a kickstart file for inclusion. Some of these packages won't work with the current distro, and during installation I get "cannot open .rpm". Currently I'm looking to find out which packages are not going to work, but it will only one package that fails at a time, at which point I have to remove the failed package from the ks, attempt to reinstall to get to the next failed package.
I was wondering if there was a way to force the installation to continue after encountering the error so that I might see all the failed packages at once, rather than going through one at a time.
I don't expect the force continue to result in a working OS, just that I might be able to see the packages that cannot be used in one attempt
Comment: Is this question about the Anaconda installer? Which distribution are you using?
Answer: just tell anaconda to ignore missing packages
%packages --ignoremissing
you will have to consult the ks anaconda file to see what was actually installed
one more option might be to add a conflicts group to the exclusion
-@Conflicts (Workstation)
to exclude packages which conflict in workstation installation for example.
EDIT
After re-reading your question I am wondering if you are referring to 3rd party packages.
If so, I would suggest a different course - either use a post install script, OR, if you intend to make this the basis of a large scale deployment - take the time to install in a virtual environment (e.g. vbox) and then install all 3rd party packages with a single yum install command. You'll get to see conflicts and bad OS version/ dependency issues interactively, which is much easier to debug IMO than reading a log after the fact.
Answer: You can always try to do 32.7. Post-installation Script and install whatever after you done with your initial install.
Comment: I like it, that might help speed things along


Evaluate this series using an integral

Question:
I've shown that it converges uniformly but am not sure what to do to evaluate the sum. Any help would be appreciated. Thanks!
Answer: Hints:
$$(1-x^2)^2x^{n-1}=x^{n-1}-2x^{n+1}+x^{n+3}\implies\int(x^{n-1}-2x^{n+1}+x^{n+3})dx=$$
$$=\frac{x^n}n-\frac{2x^{n+2}}{n+2}+\frac{x^{n+4}}{n+4}+C$$
Now do partial fractions:
$$\frac1{n(n+2)(n+4)}=\frac18\left(\frac1n-\frac2{n+2}+\frac1{n+4}\right)$$

Evaluate this series using an integral


Combining json in Python

Question: I have the below code
connection = psycopg2.connect(*******************)
cursor = connection.cursor()
sql = "SELECT schema_old FROM table_1 where ingestion_id=1;"
cursor.execute(sql)
result = cursor.fetchall()

schema_output='\n'.join(''.join(elems) for elems in result)
json_data=json.loads(schema_output)
print(json_data)

sql1 = "SELECT schema_new FROM table_1 where ingestion_id=1;"
cursor.execute(sql1)
result1 = cursor.fetchall()

schema_output1='\n'.join(''.join(elems) for elems in result1)
json_data1=json.loads(schema_output1)

where:
json_data= [{'name': 'status', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'address', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'city', 'type': 'STRING', 'mode': 'NULLABLE'}]
json_data1= [{'name': 'phone', 'type': 'STRING', 'mode': 'NULLABLE'}]

I want to combine the jsons: json_data + json_data1 , so that the final json is:
[{'name': 'status', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'address', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'city', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'phone', 'type': 'STRING', 'mode': 'NULLABLE'}]

I tried doing:
thejson1["data"].extend(thejson2["data"])

and
c = dict(a.items() + b.items())

But it did not work.
Comment: From what I can see with that formatting, `json_data + json_data1` would be enough.  You have two lists of dictionaries, they could be summed just fine.
Comment: What do you mean by "it did not work"? You got an error, the result was unexpected, something else?
Comment: Once you have read the json data with `json`, it is **just** an ordinary Python data structure of nested lists and dicts, which you work with **the exact same way** that you would if you had gotten the same data **in any other way**. The question is "I have two lists; how do I concatenate them?", and the answer is `json_data + json_data1` - exactly as you already show. The other attempts make no sense at all, as you should realize if you actually *think about the data that you have*.
Answer: Solution:
Like @Klas mentioned just the below was enough:
mjson=json_data+json_data1

Combining json in Python


Is one CLlocation2D uniquely coresponding to one place on Earth, regardless of map provider?

Question: I have this problem. I have an MKMapView and from NSLog I can see the coordinates (latitude 30.238685 and longitude 120.145461) of a place. then I put an annotation on it.
At first,the annotation is at the place i want, centered on an island.
a-------------------------------
a------+++++++++++--------
a------++++PIN++++--------
a------+++++++++++--------
a--------------------------------
then I connect some VPN. then the map provider changed. there is a bit different in terms of color, and "legal" information.
but the position of annotation changed, abit south and east from the island. then I looked up the center of the island using NSlog, it gives me another latitude (30.241080) and longitude (120.140766).
a--------------after connecting VPN-----------------
a------+++++++++++-------------
a------+++++++++++---------------
a------+++++++++++--------PIN----
a------------------------------------
I want to make sure the annotation is at the center of the island all the time.
how do i solve this issue?
..sorry, i cannot post any pictures yet..
Comment: See this regarding map coordinates issue in China: http://stackoverflow.com/questions/12511588/how-to-deal-with-inconsistent-chinese-maps-on-ios-6
Answer: Yes, the CLLocation2D is unique because it is (lattitude, longitude) couple on Earth, that does not move depending on who provide the map.
What can change is more likely the content of the map, especially on small island for instance. New-York will surely always be on the same place.
Try to put your Pin on a well-known place to see if it moves depending on map provider.


How do you enforce password complexity rules in Zotonic?

Question: I would like to enforce a password policy in Zotonic.  My first impression would be to do this as a validator on the new_password field in the Identity editor.
Here is an example policy:

Have be at least 8 characters in length
Have at least one upper case letter
Have at least one lower case letter
Have at least one number
Have at least one non-alphanumeric character
Not be based on account name

Here is a possible implementation (not tested):
string:length(Password) >= 8 andalso
re:run(Password, "[A-Z]") =/= nomatch andalso
re:run(Password, "[a-z]") =/= nomatch andalso
re:run(Password, "[0-9]") =/= nomatch andalso
re:run(Password, "[^A-Za-z0-9]") =/= nomatch andalso
re:run(Password, AccountName) =:= nomatch

How do you enforce password complexity rules in Zotonic?
Answer: What you can do is implement it as a form validation. Along the lines of the other validations.
I was wondering if there is a javascript available that shows the password strength.  (Like a traffic light, green ok, red really not ok.)
The validation can be attached using the {% validate %} scomp.
A simple password check could be done by making a single regular expression and attaching it to the password field using the format validator  http://zotonic.com/documentation/634/format
For your proposed function, or a "traffic light" functionality, it might be better to make a custom validator. Or that we add support for the Custom validator of LiveValidation, to which you then pass a Javascript function for the check.
Comment: There are a few JavaScript password checkers I have found without a graphical output. http://www.geekwisdom.com/dyn/passwdmeter is the best of those.  Using its output to drive a graphical quality meter should be straight-forward.  I will take a crack at it now.
Comment: http://phiras.wordpress.com/2009/07/29/password-strength-meter-v-2/ is much better and JQuery based as well.
Answer: My colleague pointed me to:
^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

A full explanation is available from the original author at http://davidhayden.com/blog/dave/archive/2004/09/25/501.aspx.
It has a slight bug when used in Zotonic (probably due to weirdness in the re module) so I changed the \d to [0-9] and reduced the required length to 8:
^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

It can be applied in _action_dialog_set_username_password.tpl by replacing the presence validator:
{% validate id="new_password" type={presence} %}

with a format validator as Marc W describes in How do you enforce password complexity rules in Zotonic?:
{% validate id="new_password" type={format pattern="^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"} %}


Limits on Windows environment variable nesting?

Question: So, is there a limit to how deeply environment variables can be nested in Windows? I do a lot of development work and I'm trying to set up my development environment vars, and a lot of them nest off each other, ie.

GLEW=%THIRD_PARTY_ROOT%\GLEW
GLEW_1_5_5=%GLEW%\glew-1.5.5
GLEW_BIN_PATH=%GLEW_ROOT%\bin
GLEW_INCLUDE_PATH=%GLEW_ROOT%\include
GLEW_LIB_PATH=%GLEW_ROOT%\lib
GLEW_ROOT=%GLEW_1_5_5%

OSG=%THIRD_PARTY_ROOT%\OpenSceneGraph
OSG_2_8_3=%OSG%\OpenSceneGraph-2.8.3
OSG_BIN_PATH=%OSG_ROOT%\bin
OSG_INCLUDE_PATH=%OSG_ROOT%\include
OSG_LIB_PATH=%OSG_ROOT%\lib
OSG_ROOT=%OSG_2_8_3%

THIRD_PARTY_ROOT=C:\dev\third-party

But I was having a heck of a time getting them to actually expand properly.  For a while when I looked at the output of set, I was just getting what looked like they were being expanded in order and so any ones that depended on foo_ROOT weren't being expanded properly.  I tried enabling delayed expansion and that didn't help, but restarting seemed to...  so maybe delayed expansion required a restart..
Either way, I have GLEW_BIN_PATH and OSG_BIN_PATH in my PATH variable and they refuse to expand.  This is really frustrating because the dll's are residing there and of course I can get evvvverything else to expand...  any thoughts?
I have them in the PATH variable as:
[everything else....];%GLEW_BIN_PATH%;%OSG_BIN_PATH%
So I'm not seeing an obvious cause to keep them from expanding out..
Any suggestions?
Answer: According to http://support.microsoft.com/?kbid=830473 command prompt ignores any environment variables that are inherited from the parent process and are longer than its own limitations of either 2047 or 8191 characters (as appropriate to the operating system)
May be length of your PATH with your "[everything else....];" exceeds this values?
Have you tried to add your variables to the start of %PATH%: e.g. %PATH%=%GLEW_BIN_PATH%;%OSG_BIN_PATH%;%PATH%;[everything else....];?
Comment: Hmm...  no go.  Interesting theory though.  Looking through Path, %SystemRoot% (inside [everything else]) is being expanded...  I'm really not sure what to make of this anymore...


How to insert Character as well as Integer value in a column of MySQL server 5.5?

Question: I want to insert integer as well as character value in same column depend on condition But I don't know which datatype i need to use....
Answer: The data type you need to use is VARCHAR because you can still insert string representation of an integer on that column. But if you choose to use INT, you can't insert a string on it.
CREATE TABLE tableName
(
    columnName VARCHAR(10)
);

INSERT INTO tableName VALUES ('a'); -- OK
INSERT INTO tableName VALUES ('1'); -- OK

both queries will be inserted on the table.
in the case you'll use INT
CREATE TABLE tableName
(
    columnName INT
);

INSERT INTO tableName VALUES (1); -- OK
INSERT INTO tableName VALUES ('a'); -- FAILED

the tendency is that you can't store string.
Comment: **NOTE**: If `sql_mode = 'STRICT_ALL_TABLES'` is not set then: `INSERT INTO tableName VALUES ('a');` in second table will cause insert value of 0 in `columnName`
Answer: you can use any string data type according to requirement
( char, varchar )

but  don't forgot to enclose them in single quotes
INSERT INTO tableName VALUES ('1One');

Answer: If you use varchar, all of these will produce the effect you want:
INSERT INTO atul (c1) values ('a');
INSERT INTO atul (c1) values ('1');
INSERT INTO atul (c1) values (1);

Comment: the question is tagged as mysql
Comment: In MySQL it does, but in SQL Server it will fail with this error.. `Schema Creation Failed: Conversion failed when converting the varchar value 'a' to data type int`... given `a` is the first record entering into your table column declared as `varchar`
Comment: It is also tagged in `SQL` ;) well you got it mate. The thing is it's best to encourage the `standard varchar` data insert :)
Comment: I believe that the OP wants to insert an actual integer, not the char representation of one. 1 is not the same as '1'. That's why I pointed out the case. Otherwise, you're just inserting chars ('1' is ascii 49 same as 'a' is ascii '97'). I think the tricky bit of the question was the data type he wants to insert.
Comment: Now that is a much acceptable comment. +1 for that last insert case. I tried out it works with `SELECT CAST(c1 AS UNSIGNED INT) FROM table1 where id = 2` nothing fails. It also works with any string functions as well.. like `substr`, `instr`
Answer: You can use the varchar type for that field.
For example:
create table volt_meter(
    voltage varchar(5);
)

INSERT into volt_meter values('11kv');


Converting JWT (json Web token) into key value pairs in WebAPi

Question: I can access jwt inside my web api action by accessing it's Autorization Header
string jwt=Request.Headers.Authorization.ToString();
string jwtArray = jwt.split('.');

//Now i want to convert it's payload into Key value pair.
The payload is in jwtArray[1]. Can anyone suggest how this can be converted into a KVP. I am assuming the JWT is Base64 encoded by the look of it.
Answer: Try this
var parts = token.Split('.');
string partToConvert = parts[1];
partToConvert = partToConvert.Replace('-', '+');
partToConvert = partToConvert.Replace('_', '/');
switch (partToConvert.Length % 4)
{
  case 0:
      break;
  case 2:
      partToConvert += "==";
      break;
  case 3:
      partToConvert += "=";
      break;
}
var partAsBytes = Convert.FromBase64String(partToConvert);
var partAsUTF8String = Encoding.UTF8.GetString(partAsBytes, 0, partAsBytes.Count());
// You would need Json .NET for the below
var jwt = JObject.Parse(partAsUTF8String);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jwt.ToString());

Answer: For a cleaner approach to this, Here's a helper class based on a couple of brilliant answers.
public static class StringExtensions
{
    ///
    /// Convert a normal string to base64
    ///
    /// <param name="text">Original String</param>
    /// <returns></returns>
    /// <remarks>
    /// Original Source: https://stackoverflow.com/a/60738564/8058709
    /// </remarks>
    public static string EncodeToBase64(this string text)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(text))
            .TrimEnd('=').Replace('+', '-')
            .Replace('/', '_');
    }

    ///
    /// Convert a base64 string to a normal one
    ///
    /// <param name="payload">Base64 string</param>
    /// <returns>A normal string</returns>
    /// <remarks>
    /// Original Source: https://stackoverflow.com/a/60738564/8058709
    /// </remarks>
    public static string DecodeFromBase64(this string payload)
    {
        payload = payload.Replace('_', '/').Replace('-', '+');
        switch (payload.Length % 4)
        {
            case 2:
                payload += "==";
                break;
            case 3:
                payload += "=";
                break;
        }
        return Encoding.UTF8.GetString(Convert.FromBase64String(payload));
    }

    ///
    /// Decode a JWT payload to a dictionary
    ///
    /// <param name="jwt">JWT payload</param>
    /// <returns>
    /// A dictionary representation of the jwt string
    /// </returns>
    /// <remarks>
    /// Inspiration: https://stackoverflow.com/a/31878953/8058709
    /// </remarks>
    public static IDictionary<string, object> DecodeJwt(this string jwt)
    {
        string[] chunks = jwt.Split('.');

        string data = DecodeFromBase64(chunks.ElementAtOrDefault(1));
        return JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
    }
}


Is it possible to permutate a periodic sequence in such a way that any infinite substring will always be non-periodic?

Question: In particular, I'm interested to know whether there is a shuffling method which can guarantee that the sequence of digits of a repeating decimal is turned into one of an irrational number.
Here, sequences made of just one kind of element, such as 3333... , are not of concern, since only one permutation is possible.
edit: I misunderstood the meaning of 'subsequence', therefore I removed it from the title and used 'substring' instead.
Comment: Note, that the binary representation of $\pi$ is nonperiodic but it is a subsequence of 1,0,1,0,1,0,... You don't have to permute. Every noncontant sequence has a nonperiodic subsequence.
Comment: @Jochen I suppose I misused the word 'subsequence,' then. I was intending to say something like the part of a sequence resulting from a slice.
Answer: I am a bit confused by your term substring, but I will give you several different constructions that will answer your question.
If you are looking for a permutation such that for any infinite subsequence (that is you are allowed to skip elements of the sequence), then this is impossible as since if the digit $x$ appears in the sequence, then it will appear infinitely often in the sequence, so after the permutation, you can just take the subsequence that just contains the digits $x$.
If $(x_n)$ is your periodic sequence and $(y_n)$ is the permutation, if you are curious if there is a permutation of $(y_n)$ such that for any $k$ the sequence $(y_n)_{n>k}$ (where you cut off the first $k$ terms) is not periodic. Then I claim that this can be done if and only if the initial sequence you started with is not the constant sequence. Consider the following construction. Say that $(x_n)$ has some period $k$ so we have that the sequence is $x_1,x_2,...,x_k,x_1,x_2,...,x_k,x_1,...$. Since it is not the constant sequence there exists different elements of the sequence say $x_i\neq x_j$, let us denote the elements appearing $z_1,...,z_l$ where $1<l\leq k$, then since the sequence $(x_n)$ is periodic we have that each $z_i$ appears infinitely often in the sequence, so let us form the sequence $$z_1,z_2,...,z_l,z_1,z_1,z_2,z_2,...,z_l,z_l,z_1,z_1,z_1,...$$
If you consider this sequence there is no infinite subsequence that will be periodic as you go out farther there will be arbitrarily long substring of the form $z_1,z_1,...,z_1$.


Recording self on Yamaha CP50 using USB

Question: I noticed the keyboard was advertised as being able to record directly to USB, and if i connect a USB memory stick to the back it will allow me to record for a while, but after between (so far) 30s and 5 minutes of recording the interface on the piano says 'USB read/write error' and it stops recording, which is not ideal since the piece i'm trying to record is over 6 minutes long. The piano will record successfully but only for the time before the error, so i don't think the problem is anything to do with security.
I've used 3 different USB memory sticks all with sufficient space to see if that changed anything but the problem persisted. This is the only information I could find about the problem, and it's of no use whatsoever really http://www.manualbirds.com/manuals/yamaha-cp5-owners-manual-633091-58 .  (It's for the CP5 but I believe the 2 keyboards are very similar and share a similar UI)
Any advice or information would be greatly appreciated!
Comment: Yamaha has a list of compatible USB sticks - are you using one of these? http://download.yamaha.com/api/asset/file/?language=en&site=uk.yamaha.com&asset_id=53370
Comment: When you successfully record a sample, can you tell what file format it is?
Comment: they save into .wav format
Comment: I wonder if taking an empty stick, and formatting it in the keyboard itself (if the keyboard can do this) might help. Or if not possible, format a stick in a PC or similar then try it...
Comment: Yep it looks like mine is not compatible. Strangely the 8 Gb and the 32Gb versions are... but not the 16Gb which i'm using
Comment: Have you checked for CP50 firmware updates?  Also certainly worth reporting to Yamaha and/or your dealer, especially if it's under warranty.
Answer: Based on your question, and what's been written in the comments, it actually sounds like a bug in the piano software. It could be that the piano can record a certain amount of data, but not keep up properly with the data stream, or handle errors properly, and therefore quits after a certain point, resulting in the read/write error message.
Judging by the list provided by Bacs of compatible USB drives (see comments above), it looks like it'll support most generic USB flash drives, meaning, it's not very "fussy". I suspect that a lot of testing didn't involve recording for more than a few minutes, and that's why the bug didn't show up on their radar. Or it did, but they decided to ship anyway.
Of course, without more info from other CP50 owners, it's hard to say for sure if the problem you're having is just a fluke or not. I see that model only has 3 reviews on Amazon.
But if you've tried 3 different drives, 3 different models and all have the same error result, odds are it's a bug. You could format the drives in your computer and double-check to make sure that the flash drives themselves are not defective. Use a drive utility on them just as you would a hard drive to see if it finds any errors. Keep in mind you want to do a complete "surface scan".
I have a digital Yamaha YDP-142. It has an option to initialize the settings, kind of a like a "factory reset". If yours has that option, the instructions should be in the manual. On mine it's a very quick and easy process.
Another thing you could try is figuring out which "version" your USB flash drives are that you've tried recording with: 1.0, 2.0, 3.0? And edit your question and add that information to it.
One alternative to recording using a USB drive is to use a double ended audio cable (3.5mm plug on both ends). Plug one end into the headphone jack of your piano (using a 1/4" adapter if necessary), and the other end into the AUX jack of a computer. Use Audacity or some other program to record the piano's output.
It sounds like a lot of steps, but it's really not. The biggest problem for most people would likely be having an extra computer that can sit near the piano (or just get a very long double-ended audio cable).  As for the cost of the extra equipment: Under $10 USD for the cable and 1/4" adapter. Good software to use you can find for free. As for the extra computer if you need it, if all it's going to be doing is recording, you definitely don't need anything top-of-the-line, just something that'll boot and run your recording software.

Recording self on Yamaha CP50 using USB


Run python file in child package from console

Question: This is my project structure:
/project
|    /package
|    |    __init__.py
|    |    module1.py
|    |    module2.py
|    main.py

In main.py, I import module1.py. In module1.py, I import module2.py:
module1.py
from package import module2
#do something

I run python main.py OK. But when I run python module1.py (inside package) or python /package/module1.py (inside project), I got ImportError:
Traceback (most recent call last):
  File "package/module1.py", line 5, in <module>
    from package import engine
ImportError: No module named 'package'

When I run module1.py in PyCharm, it's OK.
So, my question is : how to run file module1.py without main.py?
Thank you.
Comment: Add your project directory to [PYTHONPATH][1].

  [1]: http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7
Answer: Sol 1: When you use from package import module2 python does not know where to look for package unless its added to path. You can running it as
PYTHONPATH=/path/to/project python module1.py

Sol 2:  If module1.py and module2.py are in the same folder, you don't need to use from package import module2. Just using import module2 should be fine. Now running module1.py will work.
Sol 3: If you insist on using from package import module2. You cant append path to package in your script
import sys
from os.path import dirname, abspath
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from package import module2


Habilitar a tag contenteditable="false" para "true" com javascript

Question: Galera Como faço um script para que quando eu clicar no botão editar, automaticamente a minha div fique editável e apareça o botão salvar que ao ser clicado desaparecerá e a minha div voltara a ser não-editável?

Meu texto Que sera editado

<button class="editar">Editar</button>

<button class="btn-editar">Salvar</button>

`
Answer: Basta usar document.querySelector (pode trocar por ids ao invés de classe também, mas isto é outra história):

var salvar = document.querySelector("#salvar-frase");
var editar = document.querySelector(".editar");
var texto = document.querySelector(".texto");

editar.onclick = function () {
    // Verifica se já esta editando
    if ((" " + salvar.className + " ").indexOf(" hide ") !== -1) {
        // habilita a edição
        texto.contentEditable = true;

        editar.classList.add("hide"); //Oculta o botão editar
        salvar.classList.remove("hide"); //mostra o botão salvar
    }
};

salvar.onclick = function () {
    // Verifica se já esta editando
    if ((" " + salvar.className + " ").indexOf(" hide ") === -1) {
        // desabilita a edição
        texto.contentEditable = false;

        editar.classList.remove("hide"); //mostra o botão editar
        salvar.classList.add("hide"); //Oculta o botão salvar
    }
};
.hide {
    display: none;
}

Meu texto Que sera editado

<button class="editar">Editar</button>

<button class="btn-editar">Salvar</button>

Se desejar adicionar um foco automático ao div use .focus() e range (baseado nesta resposta):

var salvar = document.querySelector("#salvar-frase");
var editar = document.querySelector(".editar");
var texto = document.querySelector(".texto");

function setCursorEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

editar.onclick = function () {
    // Verifica se já esta editando
    if ((" " + salvar.className + " ").indexOf(" hide ") !== -1) {
        // habilita a edição
        texto.contentEditable = true;

        setCursorEnd(texto);

        editar.classList.add("hide"); //Oculta o botão editar
        salvar.classList.remove("hide"); //mostra o botão salvar
    }
};

salvar.onclick = function () {
    // Verifica se já esta editando
    if ((" " + salvar.className + " ").indexOf(" hide ") === -1) {
        // desabilita a edição
        texto.contentEditable = false;

        editar.classList.remove("hide"); //mostra o botão editar
        salvar.classList.add("hide"); //Oculta o botão salvar
    }
};
.hide {
    display: none;
}

Meu texto Que sera editado

<button class="editar">Editar</button>

<button class="btn-editar">Salvar</button>

Answer: Utilizando jQuery, seria no seguinte exemplo:

$(function() {

  $("#btn-editar").on('click', function(e) {
    $('.texto').attr('contenteditable', true);
  });

  $(".editar").on('click', function(e) {
    $(".btn-editar").show();
    $('.texto').attr('contenteditable', true);
  });

  $(".btn-editar").on('click', function() {
    $(this).hide();
    $('.texto').attr('contenteditable', false);
  });

});

    Meu texto Que sera editado

<button class="editar">Editar</button>
<button style="display:none" class="btn-editar">Salvar</button>
Answer: Um jeito diferente seria:

document.querySelector('.editar').onclick = function() {
  let label = (this.innerHTML == 'Editar' ? 'Salvar' : 'Editar');
  let inEdit = (label == 'Salvar');

  document.querySelector('.texto').setAttribute('contenteditable', inEdit);
  this.innerHTML = label;

  document.querySelector('.texto').focus();
}

Meu texto Que sera editado

<button class="editar">Editar</button>


Is risk modeling a hypothesis-driven, scientific endeavor?

Question: One could hypothesize that factors x1, x2, x3 predict y. Then, test that hypothesis using a statistical model or machine learning method restricted to those predictors while establishing criteria defining success. Yet there is still no cause/effect demonstrated per se nor an if/then relationship ventured. Given the ability of methods to "predict" given enough data and even modest manipulation, the ability to predict y will always be true given enough sample size. Risk prediction seems more analogous to having hammer, nails and wood in hand and asking "can I build a desk."
Is risk-modeling a hypothesis-driven, scientific endeavor or some other entity altogether?
Comment: Still looking for an answer?
Comment: @DeltaIV yes, I am interested in an answer.
Comment: I ask because if you are, I could write an answer.
Comment: Ok, I'll write one.
Comment: Would you also call astronomy not a science? Except for the few earth based experiments there is no way to perform randomized control studies in Astronomy. So everything is just correlating uncontrolled observations with theories.
Comment: In astronomy, I could posit that the sun revolves around the earth, gather data to test the hypothesis, form conclusions and next steps. With risk modeling, I posit that `x's` predict`y`. If I cannot predict accurately maybe I have the wrong association or model for association. If I know `x` is associated with `y` from empiric evidence the ability to predict is thus determined and whether I can accomplish prediction is a technical question not a theoretical one.
Answer: Risk modeling is a scientific endeavor, and it bears no resemblance whatsoever to DIY. Let's make a concrete example: suppose I have the following data

where $x$ is my input, $y$ is my response, the blue dots are experimental observations and the black line is the ideal model (which I wouldn't know in a real case)1. From my experimental results, it looks like $y$ has a global maximum around $x=0.5$.
Suppose now that I need a $y$ of at least 0.23 to meet my revenue target. Obviously if I set $x=0.5$, I'll minimize my chances of not meeting my targets, but I want to be more precise and quantify the risk of not meeting my target. In other words, I want to estimate
$$P(Y<0.23|x = 0.5)$$
Of course, in a real case we don't know this probability (we can only estimate it from data), but in my example I used the following generative model:
$$ Y|x \sim\mathcal{N}(x(1-x)\cos(x-0.5)^2, \sigma)$$
with $\sigma = 0.01$, thus the probability is easily computed as
$$ P(Y<0.23|x = 0.5) = \Phi\left(\frac{0.23-0.5(1-0.5)\cos(0.5-0.5)^2}{\sigma}\right) = \Phi\left(-\frac{0.02}{0.01}\right)= 0.02275013$$
where $\Phi(y)$ is the CDF of a standard Gaussian variable.
This probability doesn't depend on the number of samples we observe: only the accuracy of our estimate does. For example, using Gaussian Process Regression to estimate the ideal model, and 4 different samples of size $N=\{100, 1000, 3000, 5000\}$, here's what we get:

Our estimates changes, but the real risk probability (the probability of getting a $y$ value below the green line when $x=0.5$) doesn't:

the red line is the exact risk, while the cyan line is our estimate. Note: I used a log scale for the $y$ axis, in order to show more clearly how the estimated risk gets gradually closer to the exact risk.

1for example, $y$ could be the yield of a binary chemical reaction, and $x$ the mole fraction of one of the two reactants: if I $x=0$ or $x=1$, then I have respectively 1 or 0 of the other reactant, so the yield $y$ is 0. The yield seems to be highest around $x=0.5$, but since the actual yield is never equal to the theoretical yield, we can imagine I had to perform some experiments to get an actual yield curve (usually they look nothing like this, but it's just an example).
Comment: @Todd I used a fairly standard definition of [statistical risk](https://en.m.wikipedia.org/wiki/Statistical_risk). If you had something else in mind, you should have stated it more clearly in your question.
Comment: Your answer doesn't address the enterprise of whether risk modeling is science or not. The absence of presence of fit may be an example. If fit is not achieved, does this test a meaningful natural relationship or purely demonstrates lack of ability to model the universe of possibilities?
Comment: I just proved that risk modeling is a scientific endeavour, by estimating a risk in a consistent way, whatever the number of samples. The sentence "does this test a meaningful natural relationship or purely demonstrates lack of ability to model the universe of possibilities" doesn't make sense. If you think that the sample size affects the Type I error rate of a test, [you're obviously wrong](https://stats.stackexchange.com/a/2519/58675).


$0 \leq u_{n} \leq \frac {c}{n} \sum\limits_{k=1}^{n-1} u_{k}$ $\implies$ $\sum\limits_{k \geq 0} u_{k} < + \infty$?

Question: In this question it is proved that: $0\leq u_n\leq \frac {1}{n^2}\sum_{k=1}^nu_k\implies $ $\sum u_k$ converges.
I would be interesting in the question that whether we can relax the assumption $$ 0 \leq u_{n} \leq \frac {1}{n^{2}} \sum\limits_{k=1}^{n} u_{k} $$
to
$$ 0 \leq u_{n} \leq \frac {c}{n} \sum\limits_{k=1}^{n-1} u_{k} $$
for some constant $c \in \left( 0 , 1 \right)$. Note that we also has one term less than the previous (the series only run till $u_{n-1}$).
We can not use the same approach as in the previous question since $\sum\limits_{k \geq 1} u_{k} = + \infty$.
Comment: Are you willing to ignore $n=1$ in the hypothesis?
Answer: I am ignoring first few values of $n$ in the  hypothesis. $u_n=\log(1+\frac 1 {n+2})$ is a counterexample. Note that $\sum\limits_{k=1}^{n-1} u_k=\sum\limits_{k=1}^{n-1}[log(k+3)-log(k+2)]=\log(n+2)-\log\, 3$ from which you can see that the hypothesis is satisfied.
Comment: Note that for $n=2$, we get in the given example $u_1=\ln(\frac43) \approx 0.288$ and $u_2=\ln(\frac54) \approx 0.223$ and thus $\frac1n\sum_{k=1}^{n-1}=\frac12u_1 \approx 0.144$. That means the constant $c$ cannot be smaller than $\approx 1.5$, which is obviusly outside the specfied range.
Comment: Since the conditions are linear in $\{u_n\}$, one cannot get a lower $c$ by just multiplying $\{u_n\}$ with a constant. Even if the denominator $n$ is replaced by the more 'appropriate' $n-1$ (it is, after all, dividing a sum of $n-1$ values), that only covers values of $c \ge \approx 0.75$. It might still be interesting to know if the assumption is true for some 'small enough' $c > 0$.
Answer: With the convention that an empty sum evaluates to zero, we have for $n=1$
$$
 0 \le u_1 \le \frac c1 \sum_{k=1}^0 u_k = 0
$$
which implies $u_1= 0$. Then $u_n= 0$ for all $n\in \Bbb N$ follows via induction.
So the only sequence satisfying the hypothesis is the zero sequence, so that $\sum_{k \geq 0} u_{k}$ is (trivially) finite.

If the hypothesis is relaxed to
$$ \tag{*}
0 \leq u_{n} \leq \frac {c}{n} \sum_{k=1}^{n-1} u_{k} \text{ for sufficiently large $n$}
$$
then for any $c \in (0, 1)$ a counter-example is given by
$$
u_n = (n+1)^d - n^d
$$
where $d$ is chosen in $(0, c)$. From the mean-value theorem we can estimate the left-hand side as
$$
 u_n = (n+1)^d - n^d \le d n^{d-1}
$$
so that $(*)$ is satisfied if
$$
 d n^{d-1} \le \frac {c}{n} \sum_{k=1}^{n-1} u_{k} = \frac {c}{n} \bigl( n^d - 1\bigr) \\
\iff c \le (c-d)n^d
$$
and that is true for sufficiently large $n$.
Comment: +1 from me. Sorry about earlier correspondence.
Answer: Ignoring the condition for $n=1$, the assumption is incorrect for any $c > 0$.
To see this, define $u_1:=1$ and
$$u_n:=\frac{c}n\sum_{k=1}^{n-1}u_k, \text{ for } n\ge 2.$$
(REMARK: See below for a simplification of this proof).
This satisfies the condition of the problem, we have greedily chosen $u_n$ to be the maximal available value.
It follows for $n \ge 2$ that $u_n \ge \frac{c}n u_1 = \frac{c}n$, as the remaining terms of the sum are non-negative.
Thus we get
$$\sum_{k=1}^nu_k \ge \sum_{k=2}^nu_k \ge \sum_{k=2}^n\frac{c}k = c\sum_{k=2}^n\frac1k.$$
The sum on the right hand side is the known divergent harmonic series, and with $c > 0$ our sum is divergent by the comparison test.

SIMPLIFICATION:
After $u_1:=1$, simpy continue with the explicit definition
$$u_n:=\frac{c}n, \text{ for } n\ge 2.$$
Since $u_n=\frac{c}nu_1$, the conditions is fullfilled for all $n\ge 2$ and divergence follows the same way as above.
Comment: thanks for your observation. so what do you think about the case $0 \leq u_{n} \leq \dfrac{c}{n^{p}} \sum_{k=1}^{n−1} u_{k}$ for $1<p<2$? I took the power $1$ since I thought it would be easier in the analysis.


How to prove that $\{x\in X: f_n(x)\rightarrow 0\}$ is measurable?

Question: Let $(X,M,\mu)$ be a measure space and let $\{f_n\}$ be a sequence of measurable complex-valued functions on $X$. I need to prove that $\{x\in X:f_n(x)\rightarrow 0\}$ is measurable.
My attempt is the following: for each $n\geq 1$, we can write $f_n$ as $f_n=u_n+iv_n$, where $u_n$ and $v_n$ are real-valued measurable functions on $X$. Furthermore, it is easy to show that
$\{x\in X:f_n(x)\rightarrow 0\}=\{x\in X:u_n(x)\rightarrow 0\}\cap \{x\in X:v_n(x)\rightarrow 0\}$.
Then it suffices to show that $\{x\in X:u_n(x)\rightarrow 0\}$ and $\{x\in X:v_n(x)\rightarrow 0\}$ are both measurable.
In order to prove that $\{x\in X:u_n(x)\rightarrow 0\}$ is measurable, I have tried to express this set as the intersection or union of some countable collection of sets. But all my attempts failed. Can anyone give me a hint?
Answer: $\{x\in X:f_n(x)\rightarrow 0\}=\bigcap_j \bigcup_i\bigcap_{n\geq i} \{x: |f_n(x)|<\frac 1 j\}$. Can you show that $\{x: |f_n(x)|<\frac 1 j\}$ is measurable?
Comment: I think $\cup_{n\geq i}$ should be $\cap_{n\geq i}$ instead, right?
Comment: @OSCAR Yes, corrected


Código fonte é exibido na tela e não é executado

Question: Um código meu deu problema e ficou aparecendo alguns trechos dele em uma tela em branco quando eu executava:

O código estava certo, não sabia qual era o problema, então fui testar um outro código que uns dias atras tinha funcionado perfeitamente (eu não modifiquei ele de forma alguma, nem mesmo abri o código) e também não funcionou, aconteceu o mesmo problema dos trechos na tela:
"; } ?>

O que estou fazendo de errado?
Comment: Poste o código com problema.
Comment: O primeiro codigo "http://www.mediafire.com/download/rpczqpm3luxykmk/SistemaDeLogin.rar" e o segundo "http://www.mediafire.com/download/f92glgasmxuc8dc/TesteUpload.rar".
Comment: Coloque o código que está com problema na pergunta.
Comment: Que servidor HTTP está usando? Como instalou o PHP? Testou sem nenhum .htaccess na pasta? Se a instalação do PHP está correta, o problema é fechamento de tags. Poste o código na questão.
Answer: Isso acontece quando a short_open_tag(<?) não está habilitada no servidor, para solucionar o problema troque todas as ocorrências de:
<?

para
<?php

Outra forma é habilita-la pelo php.ini, após a alteração reinicie o servidor.
Mude o valor:
short_open_tag = Off

Para:
short_open_tag = On

Outra causa pode ser o acesso errado ao arquivo(via navegador), não funciona chamar a url fil:///c:\projeto\arquivo.php o correto é algo como http://localhost/projeto/arquivo.php
Comment: Eu tinha me esqueci que reinstalei o WAMP e esqueci de habilitar, vlw pela força mano
Comment: Não resolveu no meu, o inicío da tag já está
Comment: @CaioVieira vc mudou a forma de acessar a url?
Comment: mudei e não acessou o arquivo, eu deixei assim: http://localhost/wamp/www/meixautonomoresultados.php
Comment: com http antes de localhost
Comment: @CaioVieira http://localhost/meixautonomoresultados.php  assim vc consegue acessar?
Comment: não consegui...
Comment: @CaioVieira o wamp está ligado? qual o nome da pasta do seu projeto? se tentar só http://localhost o que acontece?


MySQL + NodeJS, SELECT return undefined

Question: Estou tentando retornar o SELECT do MySQL para fazer uma listagem, porém, quando dou um return para a função retornar o resultado do SELECT, a variável em que guardei esses dados fica com o valor undefined, segue exemplo abaixo:
JS:
sqlQuery(dbConnection)

function sqlQuery (dbConnection) {
    dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
      if (error) return console.log(error)
      dbConnection.end()
      console.log(results)
    })
  }

// Neste exemplo, o console.log lista os valores normalmente:
/*
[
  RowDataPacket {
    ID: 1,
    nome: 'Ender 3',
    producer: 'Creality'
  },
  RowDataPacket {
    ID: 2,
    nome: 'Tarantula',
    producer: 'TEVO'
  }
]
*/

Já quando tento retornar os valores dessa função e armazená-los em uma variável, acontece o seguinte:
JS:
const results = sqlQuery(dbConnection)

console.log(results) // undefined

function sqlQuery (dbConnection) {
    dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
      if (error) return console.log(error)
      dbConnection.end()
      return results
    })
  }

Como posso resolver isso?
Answer: O que ocorre é que o Node trabaha de forma assíncrona, ou seja, quando você executa a função "sqlQuery" ele não aguarda o retorno, ele já executa a linha seguinte. Por isso que o retorno é "undefined".
Para aguardar o retorno, você precisa utilizar Async/Await.  O seu código ficaria da seguinte forma:
const results = await sqlQuery(dbConnection);
console.log(results);

async function sqlQuery (dbConnection) {
    try {
      const resultado = await dbConnection.query('SELECT * FROM printers');
      dbConnection.end()
      return resultado
    } catch (err) {
        return err;
    }
}

Aqui tem mais informações:
https://codeburst.io/node-js-mysql-and-async-await-6fb25b01b628
Comment: Uma observação, dessa forma, quando um erro acontecer irá retornar o erro como se fosse o resultado esperado, uma função `async` retorna uma promessa, que possui os métodos `then` para quando ocorreu tudo como o esperado e `catch` para quando ocorre um erro, como está o erro será retornado no `then`, que espera algo diferente de um erro. Como seu `try catch` só retorna o valor ele deveria ser retirado, caso queira, por exemplo, logar no console o erro antes de retornar, pode manter mas causar a excessão dentro do `catch`
Answer: Isso é porque a função sqlQuery não tem retorno, ela recebe como parâmetro um callback que será executado de forma assincrona, ou seja, quando a consulta tiver o resultado pronto, executa a função passada, mas continua não retornando nada
Você pode criar a variável fora e setar seu valor dentro do callback:
sqlQuery(dbConnection)

const queryResults

function sqlQuery (dbConnection) {
  dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
      if (error) console.log(error)
      dbConnection.end()
      queryResults = results
  })
}

console.log(queryResults) // undefined

Observe que mesmo assim queryResults continuará com o mesmo problema, isso porque o log é executado antes do callback, que leva alguns milisegundos até ser executado (porque é assíncrono)
Você pode resolver isso com uma promessa:
const results = sqlQuery(dbConnection)

function sqlQuery (dbConnection) {
  return new Promise((resolve, reject) => {
      dbConnection.query('SELECT * FROM printers', function (error, results, fields) {
          if (error) {
              console.log(error)
              //Rejeita a promessa
              reject(error)
          }
          dbConnection.end()
          //Conclui a promessa
          resolve(results)
      })
  })
}

console.log(results) // Promise
results.then(console.log) // Os valores

Outra forma é usar async e await mas por baixo dos panos também é uma promessa

MySQL + NodeJS, SELECT return undefined


Add code to XSLT before transformation

Question: I'm using C# to transform an XML document and it is working fine:
using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

public class XmlTransformUtil
{

public static void Main(string[] args)
{

    if (args.Length == 2)
    {

        Transform(args[0], args[1]);
    }
    else
    {

        PrintUsage();
    }
}

public static void Transform(string sXmlPath, string sXslPath)
{
    try
    {
        //load the Xml doc
        XPathDocument myXPathDoc = new XPathDocument(sXmlPath);

        XslTransform myXslTrans = new XslTransform();

        //load the Xsl
        myXslTrans.Load(sXslPath);

        //create the output stream
        XmlTextWriter myWriter = new XmlTextWriter
            ("result.html", null);

        //do the actual transform of Xml
        myXslTrans.Transform(myXPathDoc, null, myWriter);

        myWriter.Close();
    }

    catch (Exception e)
    {
        Console.WriteLine("Exception: {0}", e.ToString());
    }
}

public static void PrintUsage()
{
    Console.WriteLine
    ("Usage: XmlTransformUtil.exe <xml path> <xsl path>");
}

}

The above code works perfectly, however what I want to do is, before the XSLT is transformed, I want it to add additional Lines of code to specific parts of the XSLT.
XSLT Code:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

//MAIN BODY OF CODE

</xsl:template>
</xsl:stylesheet>

How i want the XSLT Code changed in C# Before the transformation:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:include href="HEAD.xslt"/>
<xsl:include href="FOOT.xslt"/>

<xsl:template match="/">

        <xsl:call-template name="Header"/>

//MAIN BODY OF CODE

            <xsl:call-template name="Footer"/>

    </xsl:template>
</xsl:stylesheet>

How can this be accomplished?
Comment: Look instead of passing in parameters to the transform, and key off of that.  Example - http://stackoverflow.com/questions/1521064/passing-parameters-to-xslt-stylesheet-via-net
Comment: Not sure what the difficulty is. An XSLT stylesheet is an XML document, you have a tool (XSLT) for transforming XML documents, so just do it. Whether transforming the stylesheet is the right strategy here I don't know (it's a powerful technique, but there are sometimes other ways that are better), but intrinsically, if you want to use XSLT to transform XSLT, that's no problem.
Answer: XNamespace ns = "http://www.w3.org/1999/XSL/Transform";

XElement xslt = XElement.Load(sXslPath);

xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "FOOT.xslt")));
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", "HEAD.xslt")));

XElement body = xslt.Descendants("body").Single();

body.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header")));
body.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer")));

Comment: I think to have the newly added `xsl:include` with a relative `href` URL value resolve correctly you need to use `XElement xslt = XElement.Load(xXslPath, LoadOptions.SetBaseUri)`.

Add code to XSLT before transformation


One set dominating another in tournament

Question: Consider a tournament with $799$ contestants. Each contestant plays against all other contestants exactly one; there are no draws. Prove that there exist two disjoint groups $A,B$, of $7$ contestants each, such that everyone in $A$ beats everyone in $B$.
Suppose we choose $B$ by choosing any $7$ contestants randomly. If we can show that the expected number of contestants we can put into $A$ is at least $7$, we will be done. But is that true?
Answer: Edit: missed one division, so $S$ is $6$, which is not enough.
Consider the following algorithm. Starts with the set of contestant $S$ equal to everyone. By the Pigeonhole Principle, there must exists a contestant $l \in S$ that loses against at least half of the players in $S$. Put $l$ in the set $B$. Now, let $W_l \subset S$ be the set of contestants in $S$ that wins against $l$. Repeat this algorithm using $S = W_l$ 6 other times, and by the end of this, we would have put $7$ members in $B$. In addition, all the members we put in $B$ loses against the remaining members in $S$. What is the size of $S$?
$S \ge \lfloor 799/2^7 \rfloor \ge 6$.
Thus, we can pick any $7$ members of the remaining $S$ as $A$ and we have our set.
Comment: Your argument shows that there exist $6$ members that lose to a set of size $11$, and $7$ members that lose to a set of size $(11-1)/2=5$. This is not enough for the required bound.
Comment: whoops ur right.


Analyzing an unfamiliar Roman numeral analysis: Cm/G-G notated as V6/4-5/3?

Question: I was following a question, https://music.stackexchange.com/questions/57733/tips-on-how-to-add-non-diatonic-chords-to-my-music, and one of the answers introduced a chord progression involving different non-diatonic chords, with an audio sample. As I was analyzing the chord progression, I noticed something rather unfamiliar:
In the second measure a second inversion c minor chord with a V 6/4 (uppercase) roman numeration,that goes to a 5/3.
But the notation suggests it is a second inversion c minor going to a root position G major, so i 6/4 to V.

Is it just a misprint or is there something that I'm missing?
Comment: Excellent use of red freehand circles. Spot on.
Answer: That's my answer; neat!
This is a contentious issue for musicians. You're right that beat 3 is a i chord in second inversion; it has C–E♭–G, obviously a C-minor chord, and that should be i!
But let's imagine that the E♭–G–C on beat 3 didn't exist, and we just had a half note of D–G–B. We'd label that V, right? Well, this notation just shows that the V chord really "begins" on beat 3, we just have some accented non-chord tones up above. The C is a type of 4–3 suspension, the G already fits, and the E♭ is basically an accented passing tone. Especially when we have that G in the bass, our ears are already conceptualizing that beat 3 as a dominant chord. (It also helps that this particular resolution is one of the most common things in common-practice harmony; we call it the "cadential six-four.")
So to show that this is just an ornamented V chord, we go ahead and label it with a V Roman numeral, even though technically that beat 3 has all the notes of a i chord. Roman-numeral analysis tries to show how a chord functions, and since beat 3 is really the start of the dominant, we go ahead and use a V Roman numeral.
The superscript numbers just show how the upper voices are moving. The 6–5 indicates that a sixth above the bass (E♭) moves to a fifth above (D); likewise, the 4–3 shows the movement C–B.
Other methods of analysis would be:

I64–V, as you said. This is very common, but it fails to show how beat 3 is already the dominant.
I64–V, but with a bracket below, labelled V, showing that both of those chords are really functioning as dominant. This, in my opinion, is the clearest approach.

PS - Something very similar happens in the next-to-last measure.
Comment: @Richard So V 6/4  functions as a dominant even though it is a minor chord?
Comment: Yep! This is because the 6/4 really just shows the non-chord tones above the bass. Just like we label a `4–3` suspension as `V4–3`, this is just a "double suspension" of `6–5` and `4–3`, it just *happens* to create what looks like a tonic chord first. But as I said, plenty of people analyze this as `I64–V`, so both analyses are correct in their own respect.
Answer: My harmony lessons taught me that the second inversion of the tonic chord (like in the question) is notated as V 6/4 instead of I 6/4 or i 6/4, as that chord strongly tends towards the dominant. So no, it's not a misprint.
(Like you, I similarly disagree with my harmony lessons on some days.)
Answer: A Cadential Six-Four Chord progression is a chord in the second inversion that decorates two important scale degrees. The Dominant and the Tonic.
When it is the Dominant chord being decorated (like it is in this example.) then the preceding chord is the Tonic chord in the second inversion. When it is Tonic chord being decorated then the preceding chord is the Sub-Dominant chord in the second inversion.
It seems like this is just some sort of awkward printing, the better notation would be I6/4 - V5/3. May have been some printing error.
Comment: (Definitely not a printing error!)


Best ways of retrieving strings based on parsed integer code?

Question: Please ignore the topic of the post as it may sound something else instead of what I am actually asking here.
I want to make a C function which should retrieve me a string value associated with a specific integer code whose signature will be something very simple like:
char *Get_Msg (int code, char *errorInfoTable[][2]);

So, I need the strings as well associated codes stored first and because I cannot take an array of multiple datatypes, I end up storing the codes also in terms of strings as:
char *errorInfo[][2] = {

/* Error Code  Error Message
 * ----------  ------------- */
   {      "0", "No error"                                  },
   {     "93", "Error in processing"                       },
   { "-32700", "PARSE_ERROR"                               },
   { "-32600", "INVALID_REQUEST "                          },
};

Then I may just read this table in the function which in turn should return me the associated string. Firstly, is it a good way to define this table inside that function itself or as a global variable in the file. But what if I wish to store this functionality in a separate C file and call it from some other file. I see that if I declare the file as a global variable, I need to declare an extern for char *errorInfoTable[][2] in the main file and the function and then parse in the function. I want the code to calculate the number of rows in the parsed table itself. This does not seem to work if I try to calculate the number of rows withing the Get_Msg function as the function cannot see it from the formal parameter char *errorInfoTable[][2]. I can do this by mentioning the number of rows in the formal parameter or passing the number of rows as well in the function but I don't want to calculate the number of rows explicitly anywhere. I want to design it in such a way that the programmer will just add/delete the number of rows in the table and should not touch any dimensions anywhere else in the program.
Is there any other way you to store and retrieve strings from this table? or any other better ways for this functionality?
Comment: You can make an array of structures... the members of which can be of varying data types...
Comment: create a structure instead
Answer: struct { int error_code; const char *message; } errorInfo[] = {

/* Error Code  Error Message
 * ----------  ------------- */
   { -32700, "PARSE_ERROR"                               },
   { -32600, "INVALID_REQUEST "                          },
   {      0, "No error"                                  },
   {     93, "Error in processing"                       },
};

That should give you what you want. And keeping it sorted can even allow you to do logarithmic lookup.
I'd also keep the table static and inside Get_Msg.
If you need to store more data relating to the code, you would do something like this:
struct error_code_data {
  int error_code;
  const char *message;
  /* More data */
};

struct error_code_data const * get_error_code_data(int error_code);

Comment: Don't be so eager! :) The extra const you added to make the returned pointer read-only actually just applies to the temporary pointer object returned from the function. So it fills no purpose, better to just do `struct error_code_data const *`.
Comment: @AbhishekKumar, yes pretty much. static data is alive for the duration of the program. And keeping in the function reduces coupling.
Comment: @AbhishekKumar Making the table `static` doesn't make much sense if it is already a local `const`. There will be no multiple allocations of any `const` variable. It will end up in the .rodata segment no matter if it is static or not.
Comment: In other words, `typedef` this struct then have the function returning one such struct item. The table of structs should be `const` and indeed declared inside the function.
Comment: @Lundin, that's not in other words, that's something completely different. For the purpose of simple quick and dirty error code to string translation, I won't add an entirely new named struct. If there is more data to be stored relating to the code, I'd return `struct error_code_data *`, since I'm of the Linus Torvalds schools of thought when it comes to handling big struct definitions and typedefing the `struct` away.
Comment: Thanks, this sounds really perfect. You said "I'd also keep the table static and inside Get_Msg", so this will mean no multiple allocations will be done for the table (during multiple calls of the function) and it will stay alive till the end of the program. Right?
Comment: @StoryTeller Eh, return a pointer? To what? Dynamically allocated hard-copy? Non-const pointer to const struct?
Comment: @Lundin, yes you are correct. I was too eager to type to be const correct, I'm afraid.
Comment: @Lundin Concerning `static const` inside a function that "doesn't make much sense", the C11 spec §22.214.171.124 2 does that.  I see nothing in the spec about _.rodata segment_.
Comment: @chux Citing the often blatantly irrational C standard as a counter-example to "doesn't make sense" isn't the best idea... :) That being said, `static const` with an explicit storage specifier could perhaps be considered as the most formal way to declare such a variable. Similar to `auto signed int i` instead of `int i` or `extern void func (void);` instead of `void func (void)`. It won't affect the generated code. And then of course, the C standard knows very little of things like computers, memories and memory segments.


A definition of the functional $f\to\sum_{n=1}^\infty\mu(n)f \left( \frac{1}{n} \right) $, involving good functions $f$ and the Möbius function

Question: I would like to create a definition, is a conditional definition since the behaviour of arithmetic functions like to the Möbius function $\mu(n)$ depends on the veracity of the Riemann Hypothesis, that is an unsolved problem.
Any case I would like to know how create a definition with mathematical meaning. And as I am saying we are on assumption of the Riemann Hypothesis, because I believe that my definition requires this hypothesis to deduce the absolute convergence of a functional, that is its definition.
The definition is for the functional $\mathcal{F}$, from the set of entire functions (or you can do a restriction to analytic functions on an open subset of the complex plane $A(\Omega)$) to $\mathbb{C}$, defined by the rule $$f\to\sum_{n=1}^\infty\mu(n)f \left( \frac{1}{n} \right) .$$

An example. A particular value of our funtional $\mathcal{F}$, is given by $$\mathcal{F}(\operatorname{erf})=\sum_{n=1}^\infty\mu(n) \operatorname{erf}\left( \frac{1}{n} \right) ,$$ where $\operatorname{erf}$ is the Erf function, and as was said for integeres $n\geq 1$, we are denoting by $\mu(n)$ the Möbius function. Then we find that RHS is absolutely convergent, thus this particular value for the entire function $\operatorname{erf}$ is defined as a complex number.

I presume that our functional $\mathcal{F}$ will be linear (are easy justifications).

Question. How do you create a/this definition, rigurously, for the functional $\mathcal{F}$ that I've evoked, on assumption of the Riemann Hypothesis? Many thanks.

Thus I believe that is required state the domain of our functional as a subset of the linear space of entire functions, (show that is linear) and show that is defined by absolute convergence, using the asymptotic behaviour of means of the Möbius function (I presume that it is the way, and this is the reason for which is neccesary to state that we are on assumption of the Riemann Hypothesis, but if you know how create a definition without this assumption you can add it to your answer).
If there are inaccuracies in my previous words please tell me. My purpose is to know how create this definition in mathematics.
Comment: My purpose is the curiosity to know how create a definition in mathematics, based in previous ideas. I hope someone is encouraged to tell us how to define an operator of this kind. Such definition could be nice.
Answer: In fact, your functional is independent of the Riemann hypothesis.
First we note that since there are infinitely many primes, we have $\lvert\mu(n)\rvert = 1$ for infinitely many $n$, and since $f\bigl(\frac{1}{n}\bigr) \to f(0)$ by continuity, the series
$$\sum_{n = 1}^{\infty} \mu(n)f\biggl(\frac{1}{n}\biggr)\tag{1}$$
can only converge for functions $f$ with $f(0) = 0$.
If $f$ is holomorphic on a neighbourhood $U$ of $0$ and defined at $\frac{1}{n}$ for all $n \in \mathbb{N}\setminus \{0\}$, with $f(0) = 0$, then on $U$ we can write
$$f(z) = f'(0)\cdot z + z^2g(z)$$
with a holomorphic function $g$. There is an $r > 0$ such that $\overline{D_r(0)} = \{ z\in \mathbb{C} : \lvert z\rvert \leqslant r\} \subset U$, and since $\overline{D_r(0)}$ is compact, $g$ is bounded there, say $\lvert g(z)\rvert \leqslant K$ for $\lvert z\rvert \leqslant r$. Since
$$\sum_{n = 1}^{\infty} \frac{\mu(n)}{n^s}$$
is absolutely convergent if and only if $\operatorname{Re} s > 1$, the series
$$\sum_{n = \lceil 1/r\rceil}^{\infty} \frac{\mu(n)}{n^2}g\biggl(\frac{1}{n}\biggr)$$
is absolutely convergent, and hence $(1)$ is absolutely convergent if and only if
$$\sum_{n = 1}^{\infty} \mu(n) f'(0)\frac{1}{n}$$
is absolutely convergent, that is, if and only if $f'(0) = 0$.
To get an absolutely convergent series $(1)$, we thus have to require $f(0) = f'(0) = 0$. However, the series
$$\sum_{n = 1}^{\infty} \frac{\mu(n)}{n}$$
is conditionally convergent (to $0$), and so the series $(1)$ is (conditionally) convergent for all holomorphic $f$ with $f(0) = 0$.
Since only the values of $f$ at the real points $\frac{1}{n}$, $n\in \mathbb{N}\setminus \{0\}$ are used in $(1)$, we can define the functional $\mathcal{F}$ for continuous functions $g\colon [0,1] \to \mathbb{C}$ with $g(0) = 0$ that are twice continuously differentiable on $[0,r]$ for some $r \in (0,1]$. The corresponding series will then be conditionally convergent if $g'(0) \neq 0$, and absolutely convergent if $g'(0) = 0$, by essentially the same argument as above.
However, for analytic functions whose Maclaurin series converges absolutely at $1$ (in particular, functions that are holomorphic at least on some disk $D_r(0)$ with $r > 1$), we can get a nice alternate form of the functional. Namely, with the Maclaurin expansion
$$f(z) = \sum_{k = 1}^{\infty} a_k z^k$$
we obtain
\begin{align}
\sum_{n = 1}^{\infty} \mu(n)f\biggl(\frac{1}{n}\biggr)
&= \sum_{n = 1}^{\infty} \mu(n)\Biggl(\frac{a_1}{n} + \sum_{k = 2}^{\infty} \frac{a_k}{n^k}\Biggr) \\
&= \sum_{n = 1}^{\infty} \mu(n)\frac{a_1}{n} + \sum_{n = 1}^{\infty}\mu(n)\sum_{k = 2}^{\infty} \frac{a_k}{n^k} \\
&= \sum_{n = 1}^{\infty}\mu(n)\sum_{k = 2}^{\infty} \frac{a_k}{n^k} \\
&= \sum_{k = 2}^{\infty} a_k \sum_{n = 1}^{\infty} \frac{\mu(n)}{n^k} \\
&= \sum_{k = 2}^{\infty} \frac{a_k}{\zeta(k)}
\end{align}
since
$$\sum_{n = 1}^{\infty} \frac{\mu(n)}{n^s} = \frac{1}{\zeta(s)}$$
for $\operatorname{Re} s > 1$, and the change of order of summation is legitimate by absolute convergence:
$$\sum_{k = 2}^{\infty} \sum_{n = 1}^{\infty} \frac{\lvert \mu(n)a_k\rvert}{n^k} \leqslant \sum_{k = 2}^{\infty} \lvert a_k\rvert \sum_{n = 1}^{\infty} \frac{1}{n^k} = \sum_{k = 2}^\infty \zeta(k)\lvert a_k\rvert \leqslant 2\sum_{k = 2}^{\infty} \lvert a_k\rvert < +\infty$$
since we assumed the Maclaurin series converges absolutely at $1$.
Since $\frac{1}{\zeta}$ has a zero at $1$, we can also write
$$\mathcal{F}(f) = \sum_{k = 1}^{\infty} \frac{f^{(k)}(0)}{k!\zeta(k)}$$
for these functions. In that form, we have a natural extension of the functional to holomorphic functions whose Maclaurin series converges absolutely at $1$ even when $f(0) \neq 0$:
$$\tilde{\mathcal{F}}(f) = \sum_{k = 0}^{\infty} \frac{f^{(k)}(0)}{k!\zeta(k)}.$$
Comment: The norm of $\mathcal{F}$ depends on the norm we use on the domain. For the analytic function whose Maclaurin series converges absolutely at $1$, a natural choice of the norm is $\lVert f\rVert = \sum_{n = 0}^{\infty} \lvert a_n\rvert$, where $f(z) = \sum_{n = 0}^{\infty} a_n z^n$. Then we have $\lVert \mathcal{F}\rVert = 1$ and $\lVert\tilde{\mathcal{F}}\rVert = 2$, since $\zeta(0) = -1/2$ and $\zeta(k) > 1$ and $\zeta(k) \to 1$. (Consider $f_m(z) = z^m$ for $\mathcal{F}$ and a constant function for $\tilde{\mathcal{F}}$).
Comment: For $\{ f \in C^2([0,1]) : f(0) = f'(0) = 0\}$, there's not such a natural norm on the domain, but $\lVert f\rVert = \max \{ \lvert f''(t)\rvert : t \in [0,1]\}$ is a pretty good norm for that space. I'm not sure what $\lVert\mathcal{F}\rVert$ would be in that setting. $\zeta(2)$ is an upper bound, since in the notation of the answer we have $g(t) = f''(\vartheta\cdot t)$. Taking $f(t) = t^{\alpha}$ with $\alpha \geqslant 2$ gives a lower bound of $\dfrac{1}{\alpha\zeta(\alpha)}$.
Comment: Many thanks, I will need some hours to understand your very nice statements, and it seems one of the best answers that one can read in this site. Many thanks for share all justifications and the shape of your functional!
Comment: From some of your definitions (the definition for wich the calculations will be fesibles), please could tell me next week hints/how to calculate the norm of the operator $\mathcal{F}$? I am asking well for the case of continuous functions, with $g(0)=0$, $g'(0)=0$ and twice continuously differentiable on the segment, or well the second case, the analytic functions whose Maclaurin series converges absolutely at $1$ (or its particular case). If you can do it, many thanks and good week.
Comment: You're very kind/friendly, I read carefuly your remarks and refresh my functional analysis.


How can I sample from a distribution with incomputable CDF?

Question: Semi-computer science simulation related problem here.
I have a distribution where
P(x) = $\frac{(e^b-1) e^{b (n-x)}}{e^{b n+b}-1}$
for some constants b and n, and x is an integer such that $0\leq x \leq n$.
Now, I need to sample from this distribution. It has an invertible CDF, so it's possible to do this directly in theory. The problem is that the numbers involved are LARGE. So large in fact, that they both overflow conventionally formatted variables, and take at least minutes (at some point I gave up...) to compute using arbitrary precision formats. Basically, the inverse CDF still involves a term of $e^{b(n+1)}$, for $ 350 < n < 3500$. Despite this, the output numbers will still be in the range $0-n$, so it seems like there should be a way of doing this.
What I'm looking for is a way of approximately sampling from this distribution that is computable. Are there alternative methods of sampling? What are they?
Comment: Have you considered normalizing or scaling your data in some way so to reduce the domain?
Answer: The CDF is readily invertible.  A formula for the inversion leads to what has to be one of the simplest and most expedient possible solutions.
Begin by observing that the probability of outcome $k$, $0 \le k \le n$, is proportional to $e^{-b k}$.  Thus, if we generate a uniform value $q$ between $0$ and $q_{\max}=\sum_{k=0}^{n} e^{-b k}$ = $(1 - e^{-b(n+1)})/(1 - e^{-b})$, we only need find the largest $k$ for which
$$q \ge \sum_{i=0}^{k} e^{-bi} = \frac{1 - e^{-(k+1)b}}{1 -e^{-b}}.$$
Simple algebra gives the solution
$$k = - \text{ceiling}\left(\frac{\log(1 - q (1-e^{-b}))}{b}\right).$$
Here is an R implementation constructed like all the other random-number generators: its first argument specifies how many iid values to generate and the rest of the arguments name the parameters ($b$ as b and $n$ as n.max):
rgeom.truncated <- function(n=1, b, n.max) {
  a <- 1 - exp(-b)
  q.max <- (1 - exp(-b*(n.max+1))) / a
  q <- runif(n, 0, q.max)
  return(-ceiling(log(1 - q*a) / b))
}

As an example of its use, let's generate a million random variates according to this distribution:
b <- 0.001
n.max <- 3500
n.sim <- 10^6
set.seed(17)
system.time(sim <- rgeom.truncated(n.sim, b,n.max))

($0.10$ seconds were needed.)
h <- hist(sim+1, probability=TRUE, breaks=50, xlab="Outcome+1")
pmf <- exp(-b * (0: n.max)); pmf <- pmf / sum(pmf)
lines(0:n.max, pmf, col="Red", lwd=2)

($1$ was added to each value in order to create a better histogram: R's hist procedure has an idiosyncrasy (=bug) in which the first bar is too high when the left endpoint is set at zero.)  The red curve is the reference distribution that this simulation attempts to reproduce. Let's evaluate the goodness of fit with a chi-square test:
observed <- table(sim)
expected <- n.sim * pmf
chi.square <- (observed-expected)^2 / expected
pchisq(sum(chi.square), n.max, lower.tail=FALSE)

The p-value is $0.84$: a beautiful fit.
Comment: Great solution. I never knew one could sample this way (that is, relying on samples from $Uni(0, k), k>1$ instead of $Uni(0,1)$), but it is obvious in retrospect.
Answer: You're dealing with a truncated geometric distribution with $p = 1-e^{-b}$. There are a variety  of ways of approaching this.
I'd advise different options in different situations; some options would involve simulating from a geometric and regenerating when its outside the range, taking the integer part of an appropriate truncated exponential (as here), or using any of several fast techniques tailored to discrete distributions over a finite range. Given that $n$ is large, taking the floor of a truncated exponential is likely to be relatively fast, but whether it's the best choice also depends on $b$.
Here's a related question on math.SE
Before I attempt specific suggestions, what's a typical range of values for $b$?
Comment: So you have converted my question about the typical range of b to one about the typical range of ε. *Before I attempt specific suggestions, what's a typical range of values for ε?*
Comment: @Xi'an You would need $nb$ fairly small rather than $b\approx 0$ before it would be appropriate to use a uniform distribution, because the acceptance rate is $(1- e^{-(n+1)b})/((n+1)(1-e^{-b}))$ $\approx (1-\exp(-n b))/(n b)$, which will be inefficiently low when $nb \gg 1$.
Comment: Thanks for your answer! b ~ ln(1 + epsilon), where epsilon is an additional parameter > 0.
Comment: The reason I ask is which particular approaches are more efficient depends on the characteristics of the situation. It sounds like you're already happy with the other answer, so maybe it's not worth worrying about additional potential efficiency.
Comment: @JohnDoucette : If b is almost zero then your distribution is almost uniform over $\{0,\ldots,n\]$ hence you can use the uniform as a proposal in an accept reject algorithm since the upper bound should not be terrible.
Answer: First, note that $P(x)\propto e^{-bx}$ which, if $x$ were continuous, would be related to an exponential distribution. Then, what you can do is to simulate from a truncated exponential distribution  and take the floor() (integer part) of the observations.
The cdf of a truncated exponential is
$$F(x;n,b)= \dfrac{1-e^{-bx}}{1-e^{-bn}}.$$
Then, if we make $F(x;n,b)=u$, we obtain that $x=-\dfrac{1}{b}\log[1-u(1-e^{-bn})]$. If $bn$ is large, then $e^{-bn}\approx 0$ which suggest to approximate $x\approx -\dfrac{1}{b}\log[1-u]$.
rweirdp <- function(ns,n,b){
u <- runif(ns)
samp <- - log(1-u*(1-exp(-n*b)))/b
return(floor(samp))
}

rweirdp(1000,10,1)

Comment: @Xi'an Actually, this works provided `rweirdp` is modified to change `n` to `n+1`.  (As given here, it will never return a value equal to `n`: that is the effect of the approximation.)  A slightly more rigorous analysis is given in my answer. Although I obtain a different-appearing formula, it is equivalent to the (simpler!) one given here, once the `n`-->`n+1` modification is made.
Comment: I think this is basically what I was looking for. bn is always very large, proportionate sampling makes sense. Wasn't aware of the mapping, though it's clear in retrospect. Thanks!
Comment: I am glad to see that helped. I think I did not explained properly but this approach produces samples from the exact target distribution. Cheers.
Comment: @Xi'an Aren't the weights the same if one uses the value $e^{-bn}$ and take the integer part?
Comment: @Xi'an I think that term appears in the numerator of $P(x)$, up to a factorisation ...
Answer: A way to sample from the target distribution $p(k)\propto \exp\{-bk\}$ is to

run a Metropolis-Hastings experiment to determine the (interesting) support of the distribution, i.e. in which subset of $\{0,1,\ldots,n\}$ it concentrates;

metro=function(N,b,n){
x=sample(0:n,N,rep=TRUE)
for (t in 2:N){
  x[t]=prop=x[t-1]+sample(c(-1,1),1)

  if ((prop<0)||(prop>n)||(log(runif(1))>b*(x[t]-prop)))
      x[t]=x[t-1]
  }
return(x)
}

Use the support thus determined, $\{k_0,\ldots,k_1\}$ say, to compute the exact probabilities as $p(k)\propto \exp\{-bk+bk_0\}$ to avoid overflows.

Update: When thinking more about it, since $p(\cdot)$ is decreasing in k, the effective support of the distribution will always start at $k_0=0$. If $b$ is quite large, this support will end very quickly, in which case $n$ does not matter much as large values of $k$ will never be visited. If $b$ is very small, the pdf is almost flat, which means that one can use a uniform distribution on $\{0,1,\ldots,n\}$ as an accept-reject proposal. And use logs in the acceptance step to avoid overflows.


Why do odds offered by the bookmakers tend to change rapidly during the last few minutes before the start of the game?

Question: On several occasions, when checking odds offered by bookmakers, I have noticed that they have been changing rapidly as the time of the event get closer. (This was particularly noticeable during the fast few minutes before the start of the event.)
Why does this happen?
Comment: As merging the sport betting proposal with this site [is being discussed at the moment](http://discuss.area51.stackexchange.com/questions/11541/should-sports-betting-be-merged-into-sports), one of the reasons I have posted this questions was to have more questions about betting here, so that we can see how they are received.
Comment: Blog post: [What causes rapid changes in price as racetime approaches?](http://www.bettingexpert.com/blog/what-causes-sudden-changes-in-odds)
Answer: Quite simply it's because that's when there is the most betting activity - the majority of the activity, actually.
Odds start at what the bookmakers believe is an accurate representation of the outcomes.  These odds then drift or come in depending on what the punters are backing.  For example, a team might be 10/1 to win when betting opens.  If millions are bet on that then the odds will shorten.  It's not unheard of for odds to change massively in the time leading up to an event.
Consider, a football match: if a lot of money is placed on team A, the odds for team A shorten; if a lot of money is placed on team B, the odds for team A lengthen.
So now you ask: why does the majority of the activity happen just before the event?
1 - The big betters want to keep their cards close to their chests.
Say I was a professional gambler and I had really investigated the statistics and other parameters surrounding an event.  Mythical United are playing Made-up FC and Made-up FC have been set at 1/1 or evens. However, I happen to know that Mythical United are not playing four of their strongest players due to a sickness virus in the club and will be at a severe disadvantage. If I bet £1,000,000 five hours before the game then that is when the odds will change.  Because of that, everyone else will see the change of odds and might think "Oh, I'm getting some of that!"  It's a crude example but the sizeable bets are generally placed around 10-15 minutes before the event and that is why the market appears to "correct" itself.
2 - You get better value closer to the event.
The bookmaker will have more liquidity the closer it gets to the event.  For this reason, it is easier for the big boys to get large bets accepted.
3 - You're more likely to get the true odds.
It does happen - bookmakers and punters will "seed" the market so that odds are more tempting.  In horse racing you'll often see a horse at 30/1 come in to 12/1 in the build up but then drift massively out closer to the event.  You can avoid falling victim to this manipulation by betting late.
Answer: Another reason why odds change as you get closer to the event is that you have more information available.
For example in a test cricket match the odds of winning or loosing may change dramatically based on the outcome of the toss and so that isn't known until just before the start and so the odds will change.