Constraint Handling Rules in SWI Prolog: What's the order of puting a constraint to the store?

Question: I am learning Constraint Handling Rules (CHR) in swi-prolog.
I started with the tutorial from Tom Schrijvers' Constraint Handling RulesA Tutorial for (Prolog) Programmers.
The confusion part is that what's the order of putting a constraint to the constraint store?

p.69 shows that when a rule fires, add the body to (front of) query.

p.104 - p.106 show that normally, the order of putting a constraint to the store follows the query order. That is the second constraint (piggy(1)) will be placed at the right of the first constraint (piggy(5)) in the store.

p.107, according to 1, piggy(6) be added to the front of query and then be put to the store.

p.108, the strange thing happen, why piggy(4) be put to the front of the store (left to piggy(6)) ?

p.109 - p.110, more strange thing is that after the rule fired, piggy(10) be added to the store and then piggy(2) be added to the end of the store (right to piggy(10))?

My first question is what's exactly the order of putting a constraint to the constraint store?
For example,
:- use_module(library(chr)).
:- chr_constraint philosophers_stone/0, lead1/0, lead2/0, gold1/0, gold2/0.
philosophers_stone \ lead1 <=> gold1.
philosophers_stone \ lead2 <=> gold2.

?- lead1, lead2, philosophers_stone.

Why the result of the query in swi-prolog is:
philosophers_stone,
gold1,
gold2

instead of
philosophers_stone,
gold2,
gold1

The slow motion is (in my understanding):
query: lead1, lead2, philosophers_stone.
store:

query:
store: lead1, lead2, philosophers_stone.

query: gold1
store: lead2, philosophers_stone

query: gold2, gold1 <---- added to (front of) query
store: philosophers_stone

query:
store: philosophers_stone, gold2, gold1

It seems that when a rule fires, the body should be added to (end of) query? Is that right?
query: lead1, lead2, philosophers_stone.
store:

query:
store: lead1, lead2, philosophers_stone.

query: gold1
store: lead2, philosophers_stone

query: gold1, gold2   <---- added to (end of) query
store: philosophers_stone

query:
store: philosophers_stone, gold1, gold2 <--- then correct

My second question is the order sensitive?
I mean that even if the putting orders are different, the result will eventually confluent up to reordering the stable store? Can I safely ignore this order? I know that the order of rules is very sensitive in swi-prolog's CHR implementation and they can not be ignored.
Thanks.
Answer: According to both my memory and https://en.wikipedia.org/wiki/Constraint_Handling_Rules, the constaint store is a multi-set. Therefore it has no ordering at all. (If it were ordered, we would call it a list, not a multi-set.)
As for your example, I also get:
?- lead1, lead2, philosophers_stone.
philosophers_stone,
gold1,
gold2.

But also:
?- lead2, lead1, philosophers_stone.
philosophers_stone,
gold1,
gold2.

Digging a bit into the source of chr_show_store/1 and thence into '$enumerate_constraints'/2, it looks like the store is printed in the order that you declared the constraints. It also looks like each constraint manages its instances independently, that is, there is no central "constraint store" at all. Each constraint is associated with its own list of instances.
There is some ordering to execution: "Active constraint traverses the rules top-to-bottom to find any that fire", but some parts of this are unspecifed (page 214). So you're not supposed to write programs that are very sensitive to ordering issues.
As for the piggy example, it looks to me like the placement of the piggies is optimized for avoiding them moving around too much when the slides are presented during a talk. I don't think their placement is supposed to suggest an actual left-to-right order.
Comment: Also, in p.77, the author showed an example about `? - red, yellow, blue.` vs `?- red, blue, yellow.`,  the results are different. Therefore the order of "constraints in query" are definitely sensitive. Programmers have to design the rules very carefully.
Comment: "the store is printed in the order that you declared the constraints" I didn't realize it before, thanks!
Comment: "So you're not supposed to write programs that are very sensitive to ordering issues." There are 3 kinds of "order": rules, constraints in store, constraints in query. "Rules" are sensitive, "constraints in store" are not sensitive because of multi-set, what about "constraints in query"? Do you think this order must follow Tom Schrijvers' argument in p.69, i.e. must add the body to (front of) query? or could be changeable in swi-prolog implementation?
Comment: IMO, in a pure logic programming language, we should be able to reorder goals in conjunction (especially constraints). I'm curious why Tom Schrijvers pointed out "add the body to (front of) query." Or do you think I should post another question?
Comment: I *think* the "front of" part may be true when the current active constraint is being rewritten to something else, as in `a <=> b`. If `a` was active, then `b` now becomes active, so it's added at the "front" in some sense. But if you have `a ==> b. a ==> c.`, as far as I understand (and again, it's been a while), I don't think there's any fixed rule whether `b` or `c` will become active first.


How to remember high E on Guitar for tuning

Question: I've always had trouble tuning my guitar without a tuner, I try to sing a high E but end up on either C or D. Though when i hear the note E i can repeat it.
Comment: My answer [here](http://music.stackexchange.com/a/48292/28) might be helpful for you.
Comment: Check the answers to this related question (http://music.stackexchange.com/q/30186/16897) for more insight into your question.
Answer: You don't have absolute pitch. Nor do too many people. You can train your ears, but it could take years. Every time you walk past the guitar, sing that E before you play it. The guitar shouldn't be much out of tune, anyway. If it is, there's something awry with it, or where it's kept. Or ban the kids from being near it.
Stick with a tuner, or maybe better, if you don't need to be in tune with concert pitch, tune it all referencing the bottom string. Your ears will benefit, as will your sense of intervals.
Comment: I've always found it a little more stable to tune from fat to thin. Without a tuner, or reference pitch, for any string, you're stumped.Get used to tuning both ways, and find a refence point. 60 yrs ago (no tuners worth talking about then)  I had a front door key that rang a good top string. Went everywhere with me, never let me down!
Comment: After many years of playing violin, I can -- to a certain extent -- remember the pitches of the strings, enough so to tune my new ukulele by ear out of the box. But again, it's taken years. All I'd say is don't count out learning perfect pitch. I don't have it, but I can still remember four reference pitches, and that's come in handy.
Comment: @Tim as you've probably noticed, I disagree with this, respectfully.  I'm sort of hijacking your top answer, so I hope you don't object, but I think it's worth pointing out that it's perfectly possible to train your ear to remember a note even without absolute pitch, and that it's not actually that difficult.
Comment: @Tim Absolute pitch is something that is almost impossible to "learn" if you're not gifted with it. But pitch memory is a very different matter, and can be learnt relatively easily. I was being humorous earlier with the pips, I was indeed out but my disappointment was with how apparently poorly I have that particular sound committed to memory rather than my inability to use pitch memory in general. Using an A440 tone I have memorised, I can get within pretty much bob on every single time. That comes with a bit of practice, but your average musician could get nearest semitone accuracy easily.
Comment: @Some_Guy - not sure how you're hijacking it, but carry on! How you disagree when we both say it's possible to achieve absolute or near pitch, not sure either. Difficulty in achieving anything is very much subjective, so can't really be measured .`Oh, you mean downvoted!  Didn't you say you were a semitone out? I can get that close, usually closer, after some years of practice, but I don't call that absolute pitch.
Comment: @Tim Various songs I know I can pull from memory at the correct pitch work just as well as a memorised tone. I bet if you think of the intro to sweet home Alabama right now, and then check, you'll be pretty much spot on. That's not absolute pitch, that's pitch memory.  If you heard a cover played transposed you wouldn't notice, because you don't have perfect pitch. But if you close your eyes, and imagine the sound of the song in your head, it will likely come out at the right key, give or take. I'd bet good money you can do it with Fleetwood mac's the chain or the beginning of uptown funk too.
Answer: Being able to identify and/or reproduce a pitch without any reference is called absolute pitch. It's a rare ability that is not necessarily all that useful. It can even be considered harmful because people with absolute pitch are said to have difficulties with alternate tunings and transpositions.
Most musicians don't have it. What most do have, though, is relative pitch. It is the ability to identify and/or reproduce a pitch given a reference. Like when someone gives you an A and you are able to sing an E.
Even if you had have absolute pitch, it would have probably not been the best way to tune your instrument anyway. Studies show that the accuracy of people with absolute pitch is not perfect.
So my advice is to go back to using a tuner or a tuning fork like the rest of us :)
Comment: If you have a smart phone you can use a tuner application. If you have something that can play music, you can use a familiar song that you know the key of as a reference. In some countries the dial tone of land phone lines is 440 Hz which is an A. Possibilities are endless :)
Comment: @Some_Guy - you'll have to wait - maybe another 20 mins...
Comment: Sometimes there isn't one anywhere close.
Comment: U.K time pips are B. Hear them every hour...
Comment: @Tim for some reason this had never occurred to me!  As an avid radio 4 listener I am going to use this from now on!  I have to test out how well this is in my memory, I'm going to detune and retune my guitar right now!
Comment: @Tim.  I was off by nearly a semitone.  I'm a little ashamed.  I guess I'll stick to my memorised a440 after all.
Comment: Despite the upvotes, this answer is wrong.  Memorising a reference pitch you can call back and use to work out other pitches is not true absolutely pitch, but "relative pitch plus", and is a skill that can by learnt by a lot of people (anyone?)
Comment: @Some_Guy, nowhere in the answer did I claim it can't be learned. All I said was "even if you did have absolute pitch, it's not the best tuning method".
Comment: @Some_Guy I think that the Radio 4 pips are 1kHz and hence probably picked by an engineer rather than a musician.  This is a slightly sharp B, by about .2 of a semitone.  I heard a story from a musician who wrote to  the BBC to say that the pitch had dropped and it was now a true Bb and he preferred it.  Unfortunately, the response was to check and repair the circuit that made the tone.
Comment: @Some_Guy Some more information here but I cannot find a link to the going flat story. A shame, if they used 880Hz or 1046.5Hz it would be useful for tuning.  https://en.m.wikipedia.org/wiki/Greenwich_Time_Signal
Answer: I think if you know a song that has a lot of E in it, it can help you remember the exact pitch. It does for me, it is at least better than nothing really.
Answer: TL;DR  This is absolutely possible to train, and it's called pitch memory.  Most people in this thread are under the misconception that this skill is a) useless and b) requires "perfect pitch" or "absolute pitch".
Pitch memory is exactly what it sounds like, if you think of a sound that is well stored in your memory, it comes out at the correct pitch.  It's difficult to not let surrounding sounds make you accidentally transpose your own memory, but it's possible.
Personally, whenever I tune a guitar with no reference.  I use two sources, and check they are concordant.  I use a 440hz sine wave tone I have memorised, and I check it against some popular songs.
The reason I have this sine wave memorised is because I haven't used a guitar tuner (except perhaps when more than a little inebriated) in years.  I always tune to a reference pitch.  Usually I use this video, And before than I used to use the button on the micro cube that produces an a440 tone.  After many years of using it, it's been lodged in my brain.
I once knew a guitar teacher who told me said he set his alarm clock to a440 for 6 months and eventually he could sing it at will.  That might be a bit much, but it worked for him!!!
However, usually popular songs are easier than just tones, because they're more memorable. When you have something stuck in your head, or are humming it a lot, it tends to lodge in.  If you're a piano player, and you have a particular study you have played a million times, chances are, when you think of it, it comes out at the right pitch too.
I've found acoustic songs in G (like Green day - time of your life for example) which have a strong intro work well.  Similarly, sweet home Alabama, the chain by fleetwood mac, and more recently the intro to uptown funk all are lodged in my memory at the exact pitch.  You can probably think of a few songs that are too.
You want to pick a song with a strong intro, which you know very well, and preferably is in an easy key to tune from (so E A D G B of course, but also C because you can tune a G to a C easily, perfect fifths are as easy as octaves to tune to)  Stevie wonder's Superstition is great in terms of its memorability factor, but unless you're tuning to e flat, you then have to mentally move a semitone up, which is a pain. It's a little easier to focus on the memory of a song and tune to that, than to focus on the memory of a song, hum the tonic, and then move it up a semitone, especially in a noisy room.
After a quick google, I've found there are a bunch of tools online to train pitch memory too.  I've never used them so I can't vouch for them, but I imagine they're probably good.

For some reason, the comments of this thread have been focussed much more on trying to persuade you not to bother than to help you how to do it.  So for the sake of argument, why might you want to do this?

You're around a campfire on a beach and someone hands you a battered, carried on someone's back guitar.  It's not that important to get it up to true pitch, but you don't want to be too far out, because it can take the oomph out of some songs if you're flat by too much, and snap a string if you're too sharp.
Round a friend or something more's place, and they have an "I always meant to learn but never did" guitar.
Someone hands you a guitar, and you want to be able to do a quick internal check of what pitch its at without breaking out your phone.
You're somewhere with no internet connection and no tuner.

Some people are saying there isn't really a single "standard E tuning" that is "common for most guitars", because there are different standards for 'concert pitch'***
While technically correct, in almost all situations there is.  A=440.  Unless you're playing with an orchestra (who are usually just a smidgeon sharper than 440 such that it doesn't even matter), playing period correct baroque or renaissance music, or playing with someone who for some reason is convinced a440 is from the nazis and we should all play at 432 (yes, they exist) then A=440Hz.
Again, this ability is completely separate from absolute pitch, also known as perfect pitch.  However, before learning this you should already have very good relative pitch, that is to say, you should be able to, given any note, sing any other note. If you hear a C, and I ask for the A flat above it, you should be able to mentally jump up a fifth plus a semitone, and then sing the A flat.  If you can't already do this I would focus on this skill, which is truly invaluable to a musicians, especially anyone improvising or composing, before working on tuning without a tuner, which, while a lot of fun, is more of a party trick.
There are a lot of online ear training resources and videos to train relative pitch which are very good.
Comment: Not read all yet, but need to point out that, regularly, in '50s and '60s, bands which only used guitars would arrive at the studio, and all tune to the one that was best in tune already. Who cared? No-one! As long as they were in with each other, it made no difference. Listen to, and play along with some Kinks nos, while you're in concert, and you'll understand.  Quick story - in my teens, i was in a band, with another supporting us.Last no. of night, we all decided to play the no, 1 of that week. In A. Sounded awful, and after, I realised that each band was only in tune with itself.Too late!
Comment: I think some of the points in the 'rant' part would make sense more sense to me if guitars tended to wander a lot further out of tune than (in my experience) they do. The vast majority of guitars that I encounter that need a quick tune will be, if I check, less than half a semitone out; I can't remember when tuning relatively and erring on the side of tuning down wasn't good enough for a 'pick-up' situation... but obviously people's experiences vary.
Comment: @topomorto while that the case most of the time, it also isn't that rare that you come across a guitar that's completely out too.  For example, a guitar that hasn't been played for a while, transport, has been tuned to an open tuning, recently restrung with new nylon strings, victim of a kid or drunk person messing about with it. And it's certainly nice to have the peace of mind to know you're more or less at pitch, even if a good amount of the time you are anyway.  And on top of that just generally, it's a fun skill to have, which is useful in various musical situations.
Comment: I've been trying for over 10 years now, to be able to do what you say is quite easy - pitch memory. It's not easy at all, although I can get within a demi-semitone of a certain pitch 8/10 times. I don't consider this to be good enough yet to be able to tune a guitar accurately  (pitch perfect), so have to disagree with a lot of what is in this answer. And judging by the voting, it appears I'm not alone.
Comment: @Tim what technique have you been using to try to perfect this?  For me it was as simple as, every time I tune a guitar, before I start, think of a well-worn song I've listened to many a time (or memorized tone), sing it to myself, get the pitch centre, and then play the actual record and see how close I was. I would not touch the guitar at all until I had done this, the important thing is not to let any outside stimulus cloud your memory.
Comment: @Tim Sometimes I would just do it at random times of day, when it took my fancy. "Play" the intro to the song in my head, focus on the pitch centre, hum it, and then get my phone out to play the record. Checking it against a tone is pretty much useless (unless it's the tone that you're using to train yourself). A more memorable sound is better, and if you already have a few songs that you've listened to 100s of times committed to memory, you may as well take advantage of that foundation.  The important thing, though, is to always check against the thing that you're actually using as (cont.)
Comment: @Tim (cont.) internal pitch source. And the more memorable that thing is, the better. (I have a couple of things that I've been using since my late teens, not even things I listen to particularly often any more, but why stop using them now?)

The most important thing though is to regularly try it, really focus on the sound in your head first, and then, most importantly check it against the **actual sound**. Not just using a tuner for instance. Because then, each time you try, success or failure, you reinforce the memory of the thing you're using as your pitch source.
Comment: @Tim in the modern era, that's easier than ever.  Just get your phone out, and play those few seconds of music. If you really wanted to commit to it, then you could make a habit of doing it once or twice a day. Set an alarm even. At that time, try to remember the song, and "play it in your head". Then, get your phone out, play a bit of the same song, and see if it came out how you expected. If not, then by listening to how it actually sounds, you will be reinforcing the memory, and improving for next time.
Comment: After a while of this, I suspect that you'll find that your hit rate will be getting close to perfect. After a while longer, you might even get to the point where you have the focus and presence of mind to be able to do this even when there is other noise or music in the room present; to shut out other stimuli and remember one of your "pitch source" songs.
Comment: I must say, these days I don't do it nearly as often, and, when I do, I might be +/- a quartertone. But never a full semitone. For me, that's good enough to still be useful. For you, it might not be. I guess I could choose to polish it, to have it as a party trick? But I'm not likely to. And I'm not playing that much at the moment in the last year or so unfortunately, so tuning instruments just isn't something I often do. When I'm playing again more, maybe I'll work on bringing it back
Answer: From the comments it seems that you're tuning the strings in sequence from hi to low one from another.
If it's your own guitar it should stay pretty close unless you're travelling with it or introducing other environmental changes. So you can check over all the strings and tune outward from wherever the stable nucleus is.
I have some details on tuning from one external note but the important point of always tuning up leads to two kinds of checking one string from another:

scoop tuning the lower note of a tempered fourth should be slightly flatter than the perfect fourth.
nudge tuning the upper note of a tempered fourth should be slightly sharper than the perfect fourth.

So, if you tune it up from a known external high e, then:

scoop the b so it's on the underside of the perfect fourth below the e.
unison the 5th-fret harmonic on the low E with the high e.
nudge the A so it's on the upperside of the perfect fourth above the E.
nudge the D so it's on the upperside of the perfect fourth above the A.
nudge the G so it's on the upperside of the perfect fourth above the G.

and then

check the G-B is a nice major third
check E-B-G and G-B-D triads

If you always tune up, then the gears in the tuning machine are locked. If you go too far, always detune and try again from below. The guitar should mostly stay in tune from day to day.
I also use @Nae's technique of using a song either from a recording or memory.
Answer: Be more familiar with E songs.
I play roadhouse blues intro to keep my tuning in track.. it's almost unmistakable every-time.
Now high E can be adjusted with the help of low E.
Answer: Try tuning the A string first.I use Neil Young's Hey Hey My My(Into the Black) as a reference for the open A, then tune all the other strings accordingly.It stays in your head,possibly due to the way the chord rings out and resonates in the beginning of the song.No guarantees it will work for you but it usually gets me right in range of 440.


sql with group by providing unexpected result

Question: I am having a table like below
Table: variance

My result should come as

I know that the report is calculating based on sequence group when I tried to group by sequence I am not getting right out put. Is there any way to do that ?
This is what I tried. But not working
select count(sequence),values,Number
from variance
group by sequence.

I am using sybase
Thanks
Arun
Found a way to do that in a while statement. When ever I see increment in sequence increment the new sequence. Is there a way to do in a single query
Comment: And please don't use image links. Type the sample data in plain text instead. That's easier to work with and your request will still be readable in the future (when the images may have gone).
Comment: Where is the `GROUP BY`, what rdbms are you using?
Comment: where is your code ?
Comment: It seems to me you don't want to aggregate data at all, but show all records, only with row numbers instead of the stored sequence number.
Comment: Thanks I wont use image going forward. Is there a way I can do that without using a temp table or cursor ?
Comment: I need to create a new sequence based on stored sequence whenever I encounter an increment or change  in stored sequence, I need to increment the new sequnece
Answer: You probably want use row_number
SELECT row_number() over (order by sequence) as corrected_seq,
       Values,
       Number
FROM YourTable

Comment: Thanks, rownumber() will work only in sybaseIQ not in ASE. I am using Sybase ASE


Cancancan gem while using Rspec

Question: I have problem with my feature test for users creating new content. It passes only when I comment or delete this line in my controller. It looks like factory :user doesn't have ability to create new content. I checked factory using seperate test to check if it has ability to create new word and it has. What can be problem here?
authorize! :create, @word, :message => "Musisz się zalogować, aby dodać nowe słówko."

words_controller.rb
def create
    authorize! :create, @word, :message => "Musisz się zalogować, aby dodać nowe słówko."
    @user = current_user
    @word = @user.words.build(word_params)

    respond_to do |format|
      if @word.save
        format.html {
          redirect_to new_word_path
          flash[:notice] = 'Słówko zostało prawidłowo zapisane. Dodaj następne!'
        }
        format.json { render :show, status: :created, location: @word }
      else
        format.html { render :new }
        format.json { render json: @word.errors, status: :unprocessable_entity }
      end
    end
  end

user_creates_word_spec.rb
require 'spec_helper'

feature 'User creates word' do

  before(:all) do

    category = FactoryGirl.create(:category)

    10.times { word = FactoryGirl.create(:word) }

    sign_in
    expect(page).to have_content 'Wyloguj się'
    visit game_words_path
    click_link('Dodaj słówko')
  end

  scenario 'with valid input' do
    fill_in 'Angielski', with: 'house'
    fill_in 'Polski', with: 'dom'
    find(:css, ".check_boxes[value='1']").set(true)
    click_button 'Zapisz'
    expect(page).to have_content 'Słówko zostało prawidłowo zapisane.'
  end

end

test to check if user factory has ability to create new word
it "can create new word" do
  user = FactoryGirl.create(:user)
  ability = Ability.new(user)
  word = Word.new(user: user)
  expect { ability.should be_able_to(:create, word)}
end

Answer: I changed this lines:
authorize! :create, @word, :message => "Musisz się zalogować, aby dodać nowe słówko."
@user = current_user
@word = @user.words.build(word_params)

to:
@user = current_user
@word = @user.words.build(word_params)
authorize! :create, @word, :message => "Musisz się zalogować, aby dodać nowe słówko."

And it works fine. In the previous version variable @word was definied after authorize! method, so it doesn't work properly.

Cancancan gem while using Rspec


Tech differences between chrome and firefox packages apps & other html5 apps in blackberry,tizen

Question: Need to understand what are the basic technical differences between chrome and firefox packages apps & other html5 apps in blackberry,tizen.
All of them support apps in Html,Css,Js but where and how are they technically different
1.Can One app created for one platform be used for another without changes
2.If they cannot be used across then how easily can they be migrated
3.Are the differences only in manifest and main browser/os specific
Answer: I don't think there is an easy answer for this one. You'd have to probably study each platform's api layer and then do a comparison. Start with chrome.* and then research all the other platforms. If you do end up doing this, please publish your results as I'm sure many future HTML5 app developers would love to read your findings!
Comment: I would love to see such a comparison
Answer: There are 2 type of web apps.

Hosted Apps : It can be publicly accessible Web server, just like any other website.
Packaged Apps : It can be packaged sucg as a zip,wgt and so on, instead of hosting it on a web server. The apps file extension is depends on the plaform. (chrome, firefox, bbx, tizen...)

Both kinds of Web Apps are support all of HTML, CSS, JavaScript, and so on.
One difference from a hosted app is that, a packaged app must specify a platform dependant metadata such as mainfest file. And there are different device apis. For example, firefox os provides their own web api for firefox app. Tizen also provides their own web device api for tizen application.
If one application is only standard API (HTML5), then all web platform supports it (Pacakaing may be differnet.). But if application also use non-standard api(like device api which is mentioned above), it couldn't reuse.


Is the sequence $\sum_{k=0}^n\frac{1}{e^k+\sqrt{k}+1} $ convergent or divergent?

Question: I have been asked to find the limit of the following sequence
$$\sum_{k=0}^n\frac{1}{e^k+\sqrt{k}+1}$$
when $ n $ goes to infinity.
I tried to write it as a Riemann sum but the exponential term makes it quite impossible.
Any help or idea will be so appreciate.
Thanks for all.
Comment: The title is "Is this sequence convergent or divergent?".
Comment: @hamam_Abdallah: unless I am missing something $\frac{1}{e^k+\sqrt{k}+1}\leq e^{-k}$. Since the series $\sum_ke^{-k}$ converges, then so does the sequence $\sum^n_{k=0}\frac{1}{e^k+\sqrt{k}+1}$. Knowing the caliber of Mathematics you do, I think something is missing in your question.
Comment: I don't think that was the point user was making. Your title and your post are asking two different things.
Comment: @NinadMunshi Yes indeed, the answer to the title is trivially yes but find the sum in a closed form seems an harder problem.
Comment: Integral comparison could work.
Answer: That the sequence converges is clear from comparison test:
$\frac{1}{e^k+\sqrt{k}+1}\leq e^{-k}$
Since the series $\sum_ke^{-k}$ converges, then so does the sequence $s_n=\sum^n_{k=1}\frac{1}{e^k+\sqrt{k}+1}$.
From the caliber of mathematics you do, I think that that may not be what you intended to ask.  As for the value of the limit, I ignore whether there is closed form or an exact integral representation.
I think that a numerical computation is in place. I wrote a simple R script to estimate the first 30 elements of the sequence at double precision.
<code>myfun <- function(x){   1/(1+ exp(x)+ sqrt(x)) }

options(digits=15) s <- sapply(0:30,function(x){myfun(x)})

data.frame(n=0:30,S_n=cumsum(s))
</code>
One of course can write simple code to obtain multiple precision, but this is just for MSE.


HttpService Error #2096

Question: I've written a Httpservice to get data from server but when I tried to run the service it got me the error (#2096). Below is my code:
package

{
import flash.net.URLRequestHeader;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.messaging.AbstractConsumer;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

public class JSONDataLoader
{

    private var httpService:HTTPService;

    private var errVO:ErrVO;
    [Bindable]
    public var errAC:ArrayCollection = new ArrayCollection();

    [Bindable]
    public var errStr:String;

    public function JSONDataLoader(url:String)
    {
        httpService = new HTTPService();
        httpService.url = url;
        httpService.method = "POST";
        httpService.contentType = "application/json";

        var headerParams:Object = new Object();

        headerParams["Host"] = "192.168.11.59:3333";
        headerParams["Content-Length"] = 347;

        httpService.headers = headerParams;

        var parameters:Object = new Object();
        parameters["FromDate"] = "01-01-2013 18:30";
        parameters["Location"] = "String content";
        parameters["LocationId"] = 2147483647;
        parameters["ReportId"] = 9223372036854775807;
        parameters["ReportName"] = "String content";
        parameters["Team"] = "17,22,30,1,40,53,55,69,70,73,77";
        parameters["TeamId"] = 2147483647;
        parameters["ToDate"] = "01-01-2013 18:30";

        httpService.send(parameters);
        httpService.addEventListener(ResultEvent.RESULT, resultHandler);
        httpService.addEventListener(FaultEvent.FAULT, faultHandler);
    }

    private function resultHandler(event:ResultEvent):void
    {
        var rawData:String = String(event.result);
        var obj:Object = JSON.parse(rawData);

        Alert.show("Data: " + rawData);
    }

    private function faultHandler(event:FaultEvent):void
    {
        errStr = event.fault.faultString+" "+event.message;
        Alert.show("Error!!!" + errStr);

    }
}

}
What i am doing worng here. Is there problem with my headers or request body.
Please help me, as i am stuck with this from past 2 days.
Here is the full error message...
Error!!!Error #2096 (mx.messaging.messages::HTTPRequestMessage)#0
  body = (Object)#1
    FromDate = "01-01-2013 18:30"
    Location = "String content"
    LocationId = 2147483647
    ReportId = 9223372036854776000
    ReportName = "String content"
    Team = "17,22,30,1,40,53,55,69,70,73,77"
    TeamId = 2147483647
    ToDate = "01-01-2013 18:30"
  clientId = (null)
  contentType = "application/json"
  destination = "DefaultHTTP"
  headers = (Object)#2
    DSEndpoint = "direct_http_channel"
  httpHeaders = (Object)#3
    Content-Length = 347
    Host = "192.168.11.59:3333"
  messageId = "C130487E-0EBA-375E-E71D-A580EFE175EE"
  method = "POST"
  recordHeaders = false
  timestamp = 0
  timeToLive = 0
  url = "my url"
Comment: Does the service require any authentication that you need to pass through the header?  If not, I would suggest you create an html page with the input text field's names and values matched what you describe, then post to the service you write and see if it indeed returns the desire JSON string.
Comment: Also, try using something like Charles Proxy to inspect the traffic going back & forth.
Comment: Hello Tianzhen and Amy thanks for looking into this. Authentication password are not reqyuired in this service. Please can you tell what is the problem or where I am going wrong.
Comment: Hey guys, I've achieved the same through a different way. I dropped the idea of using HTTP Service and used URL Request and it worked for me. Anyways thanks for all your help. Happy coding... :-)
Answer: You may need to check if the content of the parameters contains illegal characters like '<' or '>'. Replacing them with '& l t ;' or '& g t ;' (without spaces) may solve the problem.
Errors may occur when HttpService sends or receives strings including these two marks.
Using URLRequest would be a better choice since it would be free from this problem.

HttpService Error #2096


Proof that the derivative of the prime counting function is the probability of prime?

Question: The derivative of the estimation of the prime counting function, $\frac{x}{ln(x)}$, is $\frac{ln(x)-1}{ln(x)^2}$, which is approximately $\frac{1}{lnx}$ for large values of $x$. According to the prime number theory, $\frac{1}{lnx}$ is the probability that a randomly chosen integer between 2 and $x$ is a prime number.
Why is the derivative of the prime counting function the probability of getting a prime number?
Edit: I've only studied up to basic integrals, so try to keep it simple!
Answer: You are describing Cramer's model of the primes, which is pretty good. However, Maier showed about 1985 that it gave incorrect estimates for short intervals. See if i can find it, it's a famous episode.
Maier's theorem
Answer: This is not precise, because $\pi(x)$ is neither continuous nor differentiable, but you get the idea :-)
Mean value theorem:
$$
\pi(x+1)-\pi(x)=\pi'(\xi)[(x+1)-x]=\pi'(\xi)
$$
for some $\xi\in(x,x+1)$. But $\pi(x+1)-\pi(x)$ is either zero or one according to whether $x+1$ is prime or not. So probabilistically we get the result you described. Or you can look at a longer interval.
Comment: Can you explain the equation? And what do you mean by "probabilistically we get the result you described"? I should've mentioned that I'm in high school, so I don't really understand what you mean.
Comment: @LeoJiang That equation "follows" directly from the MVT as stated in the post https://en.wikipedia.org/wiki/Mean_value_theorem#Formal_statement. Take, $a=x$, $b=x+1$, and $f=\pi$. As said, the analysis in the post is not precise, but gives a rough idea of what should be happening.
Answer: The reason for calling it a probability (or better, a probability distribution), is because when we are given a probability distribution with density $p(x)$ at event x then by the definition of such a density, we expect the total probability $P(a \le x \le b)$ for an event to occur between a and b to be given by
$$P(a \le x \le b)=\int_a^b p(x) dx$$
By the Fundamental Theorem of Calculus, then, we can expect that p will have a differential relation to P here, and P will be $\pi(z)$ if a is 2 and b is z.  This is why you see the differential relationship you ask about.
Now, we actually are not looking at probabilities here, as the integrations clearly can be greater than 1.  So maybe the confusion is why call this a probability at all.  Well, there are two related reasons.  First, what P really is when we use the expression above is the "expected number of primes between a and b", if we assume primes are distributed randomly.  This is still a probabilistic function, so the term probability is often used loosely.  More rigorously, though, something called "extended probabilities" can be used for just this kind of circumstance, and we can just relabel things here.  So there is a sense we are really talking about a probability, just not one from 0 to 1.  And we could use this to define the probability of finding one prime between a and b using common statistical techniques (it looks nothing the probability you mention, though).
However, this way of looking at p is used really loosely in general.  Clearly, Bertrand's postulate (theorem) ensures a prime between n and 2n with certainty, so the random distribution has some constraints.  We know if p (>2) is prime, then the next number p+1 has 0 probability of being prime (and similarly, if p and p+2 then not p+4, etc.). And we know other relationships that affect higher moments of prime distribution as well.  This talk is just to get a very basic first order look at primes because we don't have an easy function that shows their distribution, but we can flatten it out with approximations and look at those.  That's the point of the Prime Number Theorem, to take that big view and see what we can understand just by squinting hard enough.


How to make a variable empty if it will not find the item?

Question: I have Lessons and have Test for the Lesson. I am looking for particular test, which exists for some lesson and doesn't exist for some Lessons.

My Question is How to make variable test as empty array if it will not found the data?

$test = Test::where('level', 'medium')->where('lesson_id', $lesson->id)->firstOrFail();

I mean if the code above item doesn't exists, how i am gonna assign it as empty array, I am getting Error cause for some cases it is not finding the data, I tried to put code inside try and catch but didnt helped me!
Comment: Neither `firstOrFail()` nor `first()`, will return an array. Is that really what you want?
Comment: Can you show how you're using/testing the data i.e. where you're testing to see if it's empty?
Answer: firstOrFail should throw an exception so in try catch you should be able to resolve it, another approach is the following:
$test = Test::where('level', 'medium')->where('lesson_id', $lesson->id)->first() ?? [];

the ?? operator means if the result of the first part is null it will return the empty array.
Answer: firstOrFail() function return first found item, but if item doesn't exist, it throw exception ModelNotFoundException. I don't know why you want to put empty array here, but that is solution for your case:
$test = Test::where('level', 'medium')
    ->where('lesson_id', $lesson->id)
    ->first(); // this returns null if item doesn't exist
$test = $test ?? []; // this turns null to empty array

Beter solution is to take null from query result and check it in if. Example:
$test = Test::where('level', 'medium')
    ->where('lesson_id', $lesson->id)
    ->first();

if (!$test) {
    // do this, if item doesn't exist
}

or like that:
try {
    $test = Test::where('level', 'medium')
        ->where('lesson_id', $lesson->id)
        ->firstOrFail();
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
    // do this, if item doesn't exist
}

Answer: To get data from database or an empty array (collection) if there is no matching data,  you may use get() function on query builder.
$test = Test::where('level', 'medium')
            ->where('lesson_id', $lesson->id)
            ->get();

Answer: you could use exists() or doesntExist() to check if records exists or not.
$test = Test::where('level', 'medium')->where('lesson_id', $lesson->id)->exists();


Error handling of AVAudioPlayer's contentsOfURL:error: in Swift 2

Question: I followed a tutorial re: how to create an MP3 Player in Swift and I encountered a spot where the syntax has changed between Swift 1.2 and Swift 2.0.
I've encountered an issue with error handling for the following method:
player = AVAudioPlayer(contentsOfURL: url, error: &error)

I'm aware I need to use try and catch to "Swift2-ify" it. I've done an "apples to oranges" translation of the Swift 1.2 code, but I'm having difficulty making it "apples to apples".
Here are the relevant methods/declarations from the tutorial in Swift 1.2.
var player: AVAudioPlayer?

func queueTrack(){
    if (player != nil) {
        player = nil
    }

    var error:NSError?
    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)
    player = AVAudioPlayer(contentsOfURL: url, error: &error)

    if let hasError = error {
        //TODO: SHOW ALERT HERE
    } else {
        player?.delegate = self
        player?.prepareToPlay()
    }
}

Here is what I attempted in Swift 2.0. It runs, but I get warnings.
func queueTrack() {
    if (player != nil) {
        player =  nil
    }

    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)
    // I get a warning to make 'var error' to 'let error' here
    // If I do what the compiler says, I get a warning the error isn't
    // initialized after 'catch' outside the curly braces
    var error: NSError? // TODO: figure out how to remove this warning

    do {
        player = try AVAudioPlayer(contentsOfURL: url)
    } catch {
        NSLog("Unresolved error \(error)")
        // SHOW ALERT OR SOMETHING
    }

    // Immutable value 'hasError' was never used; consider replacing
    // with '_' or removing it
    // If earlier declaration of error is changed to let, the warning turns
    // into an compiler error

    if let hasError = error {
        // show alert
    } else {
        player?.delegate = self
        player?.prepareToPlay()
    }
}

What mistake have I made in my translation?
Answer: You don't need var error: NSError? anymore at all, delete it and the related lines.
Now you handle the possible error in the catch block.
func queueTrack() {

    let url = NSURL.fileURLWithPath(tracks[currentTrackIndex] as String)

    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        player?.delegate = self
        player?.prepareToPlay()
    } catch {
        NSLog("Unresolved error \(error)")
        // SHOW ALERT OR SOMETHING
    }

}

Note that this error variable in the catch block is not the same variable as before, it's a new one (of type ErrorType) generated by the catch block.
There's another syntax for the catch block:
    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        player?.delegate = self
        player?.prepareToPlay()
    } catch let error as NSError {
        NSLog("Unresolved error \(error.debugDescription)")
        // SHOW ALERT OR SOMETHING
    }

Here the error will not be ErrorType but NSError as usual.
Comment: Awesome! Thank you for getting me squared away so quickly and succinctly. I greatly appreciate your help on this.


Why do you need meter in music?

Question: The music score clearly specifies the length of all notes. So once you know how long a quarter note should last, for example, you already know the tempo and timing of entire score.
So why would you need to specify meter? I understand that the part of meter specifies the length of a note in terms of number of beats but I don't understand why we also need to specify the other part for where to place the bar.
Does it really matter if I decide to place bars every 4 beats or 8 beats? Is it really only for emphasis? What if I don't want any emphasis for my composition?
I tried playing simple tunes in software by only changing its meter and did not hear any differences for same score but different meters.
Comment: Try thinking up a musical phrase and sing it to yourself. Sing it in the style of a marching band, or a waltzing princess, or a plaintive slave, or a fervent Methodist, or ... Each time you will feel the stress and meter of each bar come through, the precise rhythm of the marching feet, the romantic sway of the dance. That's what your software failed to replicate.
Comment: [Documentary about Steve Reich's music](http://www.youtube.com/watch?v=3xON0AAYdVw&feature=share&list=PLQGiCocGL5poddtRpduDRBKuWw_tNv1Uk) One of the later parts describes music with "multiple candidates" for the downbeat.
Answer: As you say, "only" for emphasis - but emphasis is hugely important. People like music to have a pulse.
A musician would play these two lines differently, and someone with a musical background would be able to tell the meter just by listening:

There is a lot of subtlety to phrasing, but in blunt terms:

They would play the first note of each bar slightly louder
They would take a slight pause at the end of each bar

A computer program designed to mimic a human player would also make those two lines sound different. The programs you tried, either don't attempt anything so ambitious, or you had options turned off.
Although formally, every quarter-note is the same length, in actual performance, some notes are "pushed" and come early, and others are "pulled", and come late. This happens with the meter - for example, the third beat of every bar might be pulled.
To a large extent, human players can't help adding "swing" or "groove" by pushing an pulling notes, so the style that's the biggest exception is early sequenced electronic music, and subsequent music influenced by it. It didn't take long for sequencer designers to add a "swing" slider.
Some composers have written music with no meter. This is known as "free time". Eric Satie's Gnossiennes are some examples.
Comment: That Satie piece comes out as closer to 6/8 time although it's written in '4'.Even he put emphasis on certain notes, which meant it could have been written slightly differently, to give a better clue to the reader.Without bars, it can be played in so many ways,maybe Satie didn't want to specify too closely; this is a good reason for having bars.
Comment: The player and the computer should not play it as such. It should be a choice in the mind not on the paper. Latin players for example like to accentuate the `ah` more than the first beat. That doesn't mean they write in a shifted pattern.
Comment: Several aspects of the Satie point to it being in effect in 3/2, despite the lack of bar lines. The left-hand's broken chords give a sense of a downbeat every 12 notes. The fact that the harmony only ever changes at these downbeats strengthens this impression. 6/4 would also fit, but the beamings of the LH quavers/8ths in fours, and the spelling of some of the RH rests, indicate 3/2.
Answer: Apart from the great answers talking about phrasing and emphasis, another purely technical consideration is synchronization.
If you don't have bars, it's very difficult to get everyone in an ensemble to rehearse a specific passage or phrase together.  You could add rehearsal letters to a free-time score, sure, but it's very easy to say "ok, let's try it again from bar 58."
You also need some kind of sync points with the more complex and faster meters.
If you can, take a listen to the fast passages of The Sorcerer's Apprentice (Dukas) for instance. You might imagine this is in 9/8 and beaten in three - but it's not. It's in a very fast 3/8 and beaten in one.  Without meter and bars, you could never get everyone together - it would be chaos.
(The joke here is that he didn't use 9/8 because Disney was paying him by the bar ;-)
There are also cases where composers like to play with the emphasis.  Alfred Reed, for example, likes to use 5/4 bars but alternate the emphasis: 2+3, 3+2, 2+3, 3+2.  Again, bars here help to keep you aligned as you play. Some composers (no name occurs to me at the moment) also score in one time signature, but place accents so that the music sounds like it's in another (these really mess me up).
Hope that helped too :-)
Edit:  Here are a few interesting usages of meter from "El Camino Real" (Reed).

Showing the emphasis split within a bar - the conductor will usually conduct here in three, with the downbeats on the emphasis points.

Lazy meter changes - the double time signature here tells us that Reed's going alternate 4/4 with 3/4, and isn't going to write the changes in every time.  This only lasts for 4 bars though.

Meter change with emphasis - this section, which is a rather slow fandango, Reed starts out in 5/8 (emphasis 3+2), but as the fandango section gets going, goes into 8/8 beaten in 3: 3+2+3 per bar.  Notice that in these long bars there are no accents written.  The emphasis guide tells you how to stress the first note of each group.
Answer: Most music naturally falls into rhythms. It's what makes music work in most cases. If one is trying to dance to it, it needs to be in rhythm.All the time signature (meter?) is there for is to tell the player/reader what to expect, without having to check out any further. 4/4 is so common, it's often stated with a 'C': when I write out music,in 4/4, I don't put time sig., as it's the default time.Thus, I only put numbers when it's NOT 4/4.
                                                                                If it is not stated, looking at the bars may not help to anticipate the 'feel'. 3/4 has, for example, 6 quavers (8th notes) per bar, as does 6/8. But the feel of each is very different.Think 'Silent Night' - 3/4 or 6/8, or - does it matter? O.K., convention says they should be grouped differently, but to take your argument one step further.......
                     Yes, it's mainly for emphasis, initially at least, so the reader has a chance to recreate what the writer meant. Sometimes, when writing music, it's not easy to decide if it's 2 time or 4 time, but in deference to the guy who is going to read/translate it, a clue needs to be left.
When playing by yourself, maybe it matters less. In an ensemble situation(or a band/orchestra) it's very important, before everyone starts, that they all know the 'feel' of the piece. Yes, often, a tune is played 'cold' with NO rehearsal, and in these circumstances all clues are vital.
Answer: On a technical level you are right; note that the MIDI format has no meter but simply states "this note so loud so long" (the last one indirectly by a follow-up note-off event). The note representation is still clumsy in total however and so needs additional information in the form of text ("funeral march"), articulations, accents and so on. To reduce the amount of information to be applied to each note, a systematic pattern like a meter surely helps. Anybody who has struggled with a piece interchanging 3-beat and 4-beat passages is likely to confirm this. So there may be pieces, which don't benefit from a meter, but I'm not convinced there are many. I consider "only for emphasis" an understatement hardly to exceed, music lives from contrasts.
Answer: So why would you need to specify meter?
My personal take on this is that you write a score in order for other musicians to play the music. The aim should be to convey as much of the intended music in as readable format as possible. Following established conventions in the score helps musicians performing the music better.
You might compare this with written words. NOT WRITING ALL IN CAPS does help the reader. But sometimes, say when writing poetry, you may want to brEAk all the ruLEs and wrITe things diffERentlyyyyy to convey something, maybe a feeling.
So, no, there is no absolute need for specifying the meter. You use it to help musicians read the music and play as intended.

Why do you need meter in music?


Printing first occurence of multiple files with awk

Question: I have .txt files in subdirectories and I wish to extract the first occurrence of a string in the 4th column in the line where the string "CHEESE" is contained.
The code I am using is below:
awk '/CHEESE/{print $4}' ./*/*/*.txt | pr -15s',' > ofile.csv

This one does not work because it prints ALL occurrences of the string in the specific columns of all files.
I tried adding the 'exit' as below:
awk '/CHEESE/{print $4;exit;}' ./*/*/*.txt | pr -15s',' > ofile.csv

This printed one occurrence - but only in one file.
How can I make this print only one occurrence for all files?
Thank you in advance.
Answer: This should do:
awk '/CHEESE/ && f!=1 {print $4;f=1}' ./*/*/*.txt | pr -15s',' > ofile.csv

It will only print if f is not set.  When find CHEESE, set f, so no more printing
Answer: If you are using gawk, you can try the nextfile statement.


Conceptual question about taxonomy structure

Question: Imagine i want a directory of different organisations in different locations. Let's say i have

hospitals
retirement homes
yogashops
health-insurance agencies
(...)

in

Boston
Detroit
Denver

I would create an overview listing of the cities to link them to the organistaions-categories of each city. These would be links to a view of all organisations of the chosen type in the chosen city.
What i already have is a vocabulary "organisations" and a vocabulary "cities". I have created a view with a contextual filter "organisations" which lists all items of an organisation-term:
organisations/yogashops
But how can i prepend the selection of a specific city?
Do i have to create a vocabulary of organisations for every city? Even if they are the same?
How can i reuse my "organisations"-vocabulary?
EDIT: Would it be an alternative to create a node for each city and then use them as entity reference for the categories?
Comment: I'd create a node type with both vocabularies in it. Then I'd create a custom view showing list of organizations in each city(assume city is selected) collecting them from the eligible nodes.
Comment: @AgA - Putting your answers in the answer form below allows it to be picked by op as *THE* answer. ;) Allows others to upvote your answer, giving you some oh-precious karma. Thanks for contributing!
Comment: Volker did I understand your question correctly?
Answer: If I understand the question correctly you want to prepend the city name as an argument on the view, so you would have:

organisations/denver/yogashops

well you could equally have the city appended:

organisations/yogashops/denver

The question has no mention of Views, but I would recommend that you create a view with the contextual filters of organisation and city:

I recently set up something similar for global dealerships /find-a-dealer/europe/fr
Comment: Actually i want the city first, like: denver/yogashops/smith. But i guess this will work as well with views and contextual filters?
Answer: can't you just add a second contextual filter to your view, for cities,
and use the thrid url parameter as input ?


Which of this two A/B test set-up is better?

Question: My goal is to conduct an A/B test to compare if our new customer ranking algorithm is better than the old one in terms of conversion rate (for our call center). I have two set-up scenarios in mind but struggling to figure out which one is better.
Set-up 1:
Every time a customer comes in, randomly put the customer into either pool A or pool B (50/50). Then when a contact center representative tries to claim a customer, randomly assign the representative to claim either from pool A or pool B (50/50). If the representative is assigned to pool A customers, then use the new ranking algorithm to pick the top 1 customer in pool A otherwise use the old ranking algorithm to pick the top 1 in pool B.
Set-up 2:
Put all customers in one pool. Every time a contact center representative tries to claim a customer, randomly decide whether to use the new ranking algorithm or the old one (50/50). Then pick the top 1 customer based on the ranking algorithm selected.
I have a feeling that set-up 1 is a cleaner way but I cannot find a scenario demonstrating that set-up 2 is flawed...
Thank you so much for your help!
Answer: It's the same thing. I think you are just confusing yourself by calling each pool of customers A and B when really you're AB testing the new ranking algorithm vs the old. As long as each person in your sample is randomly assigned to either A or B and the split is even then it doesn't matter. In this case set-up 2 would actually be better as you aren't wasting a step into separating into two arbitrary groups.


Quais são as principais vantagens de se utilizar o recurso de modularização do Java 9+?

Question: A partir do Java 9 temos a possibilidade de modularizar nossa aplicação utilizando o chamado Java Platform Module System
Antes do Java 9, a modularização era feita puramente através de JARs, onde tinhamos várias bibliotecas, e era possível modularizar a aplicação com vários JARs (por exemplo, criar JARs contendo apenas entidades, contendo utilitários, anotações...)
Desta forma, levanto os seguintes questionamentos:

Que ganho expressivo temos ao utilizar o novo sistema de módulos?
Em termos de complexidade, o quão fácil é sua aplicabilidade em projetos grandes que já estão rodando em Java 8 por exemplo?
Durante atualização de bibliotecas, volta e meia nos deparamos com conflitos entre versões e dependências. Nesse cenário de modularização, este problema não se torna mais comum?
Answer:
Que ganho expressivo temos ao utilizar o novo sistema de módulos?

Aqui, pelo que pude ler e sentir o sabor (não pude sorver um grande gole, apenas uma provinha na ponta da língua) do Jigsaw, são duas as principais vantagens:

você pode criar classes que não irá expor e usar em qualquer pacote do seu módulo
otimização da busca da classe pelo classpath

A primeira parte inclusive eu senti quando se tentou colocar um código legado para rodar com Java 12: a Oracle, agora, resolveu esconder de fato as implementações íntimas dela.
Não sei se você lembra, mas sabe os pacotes sun.java.*? Pois bem, eles eram pacotes internos que deveriam ser consumidos apenas pela JRE/JDK da Sun/Oracle. Em tese, nenhum programa feito para rodar em Java deveria depender desses pacotes. O que foi possível fazer com o Jigsaw? Removê-los do caminho =) Aí o que aconteceu com uma biblioteca legada que eu tinha que acessava sun.misc.BASE64Encoder? Deu ClassNotFoundException e o sistema parou.
Sinceramente, eu achei ruim? Não, por incrível que pareça não achei ruim. Apenas curioso. Como o código a essa biblioteca foi perdido no espaço/tempo (e ela é um artefato depreciado), serviu apenas como mais um empurrão para abandoná-la.
Agora, como você obtém uma performance melhorada na busca pelo classpath?
Vamos voltar à classe que eu não tinha mais acesso, sun.misc.Base64Encoder. Quando se está em um módulo, a primeira busca será por classes daquele módulo. Então, no caso do módulo java.base (vamos fingir, ok? Não sei qual seria o módulo real), em dado momento foi necessário acessar à classe sun.misc.Base64Encoder. O processamento estava dentro do módulo java.base, então a primeira coisa que ele faz é inquirir dentro do módulo quem é sun.misc.Base64Encoder e ele encontra essa classe, pública.
Agora, estamos na minha implementação. Suponhamos que ela esteja devidamente portada para Java 9 e tenta acessar sun.misc.Base64Encoder. A primeira coisa que o ClassLoader tentará fazer será ver, dentro do módulo em que me situo, se tem alguma classe com essa assinatura. A resposta será não. Então, nesse momento, percorro também todos os outros módulos do classpath que declaro usar (ou herdo via transitive) e vejo se tem alguém que provê o pacote sun.misc, sem entrar neles profundamente para mais inspeções. Talvez uma ou outra biblioteca em Java 8- ofereça alguma resistência pois, por padrão, elas se comportam como se fossem módulos com todos os pacotes disponíveis.
Viu como o tempo de busca é reduzido usando módulos?

Em termos de complexidade, o quão fácil é sua aplicabilidade em projetos grandes que já estão rodando em Java 8 por exemplo?

Você consegue modular bem o seu programa? Se sim, o primeiro passo será disponibilizar um module-info.java com as seguintes informações:

quais são os módulos que eu dependo? requires
para cada módulo requerido, devo deixar disponível para terceiros que importam do meu módulo ou não? transitive
quais pacotes vou expor programaticamente para que seja enxergado como parte do classpath para outros módulos? exports
quais classes gostaria que fosse acessível via reflection, mesmo que não esteja "disponível" para acessar diretamente pelo ClassLoader´?opens`

Esse passo do opens é o mais delicado quando se usa um framework que dependa bastante de reflections (como Spring, Hibernate, MyBatis etc).
Definindo tudo isso corretamente, e fazendo a separação adequada dos módulos, o resto devo fluir naturalmente. Eu particularmente vejo mais aplicação do Jigsaw para bibliotecas, mas não vi motivos para impedir de uma aplicação ser separada em módulos.
Agora, essas definições não são triviais de se fazer. Talvez uma reengenharia do código original para esconder a implementação movendo-a para outro pacote seja necessário.

Durante atualização de bibliotecas, volta e meia nos deparamos com conflitos entre versões e dependências. Nesse cenário de modularização, este problema não se torna mais comum?

Uma vantagem que esse esquema fornece é poder ter diversas classes com o mesmo nome. O único requisito para isso é que elas não sejam de pacotes exportados. Uma biblioteca muito bem bolada possa conseguir fazer o uso adequado disso, mas a maioria é falta com target para Java 8.
Outro ponto é que isso não exime o gerenciamento de dependências pelo Maven ou Gradle (ou aquilo que você usa para este fim). Então, não vejo como o uso de módulos diminuiria esses problemas de atualização (com possível exceções de classes com a mesma assinatura em dois módulos distintos).

Referências:

https://www.baeldung.com/project-jigsaw-java-modularity
https://openjdk.java.net/projects/jigsaw/


Give a closed formula for the recursive series of $S_1 = \frac{a_1}{b_1}, S_{n+1} = \frac{a_{n+1}}{b_{n+1}+S_n}$

Question: The Problem:
The following real numbers are given:
$$a_1,a_2,a_3,...\in\Bbb{R}\backslash\{0\} \\
b_1,b_2,b_3,...\in\Bbb{R}\backslash\{0\}$$
We define a recursive series of:
$$S_1 = \frac{a_1}{b_1} \\
\forall n \in \Bbb{N}^+: \quad S_{n+1} = \frac{a_{n+1}}{b_{n+1}+S_n}$$
What's the closed formula for $S_n$, which includes the values of $a_1,...,a_n$ and $b_1,...,b_n$?
My attempt:
Assuming that $S_n$ can be written up as
$$S_n = \frac{a_{\text{old}}}{b_{\text{old}}}$$
We can deduce that
$$S_{n+1} = \frac{a_{n+1}}{b_{n+1}+\frac{a_{\text{old}}}{b_{\text{old}}}} = \frac{a_{n+1}}{\frac{b_{n+1}b_{\text{old}}+a_{\text{old}}}{b_{old}}} = \frac{a_{n+1}b_{\text{old}}}{b_{n+1}b_{\text{old}}+a_{\text{old}}} = \frac{a_{\text{new}}}{b_{\text{new}}} \ \ (*)$$
So if $S_n$ can be written as a simple fraction, $S_{n+1}$ can too. Since $S_1$ is a simple fraction, all $S_i$ can be written as simple fractions, and the above formula gives us the way to do so.
At this point, I wrote up the first $5$ members of the $S$ series:
$$S_1 = \frac{a_1}{b_1} \\
S_2 = \frac{a_2}{b_2+\frac{a_1}{b_1}} \stackrel{(*)}{=} \frac{a_2b_1}{b_2b_1+a_1} \\
S_3 = \frac{a_3}{b_3+\frac{a_2}{b_2+\frac{a_1}{b_1}}} \stackrel{(*)}{=} \frac{a_3b_2b_1+a_3a_1}{b_3b_2b_1+b_3a_1+a_2b_1} \\
S_4 = \frac{a_4}{b_4+\frac{a_3}{b_3+\frac{a_2}{b_2+\frac{a_1}{b_1}}}} \stackrel{(*)}{=} \frac{a_4b_3b_2b_1+a_4b_3a_1+a_4a_2b_1}{b_4b_3b_2b_1+b_4b_3a_1+b_4a_2b_1+a_3b_2b_1+a_3a_1} \\
S_5 = \frac{a_5}{b_5+\frac{a_4}{b_4+\frac{a_3}{b_3+\frac{a_2}{b_2+\frac{a_1}{b_1}}}}} \stackrel{(*)}{=} \\ \stackrel{(*)}{=} \frac{\begin{matrix}a_5b_4b_3b_2b_1+a_5b_4b_3b_1+a_5b_4a_2b_1+ \\ +a_5b_4a_2b_1+a_5a_3b_2b_1+a_5a_3a_1\end{matrix}}{ \begin{matrix}b_5b_4b_3b_2b_1+b_5b_4b_3b_1+b_5b_3a_2b_1+b_5a_3b_2b_1+ \\ +b_5a_3a_1+a_4b_3b_2a_1+a_4b_3a_1+a_4a_2b_1\end{matrix}}$$
I can definitely see some structure, but it becomes chaotic after a while. It would be incredible if we were to come up with a formula like:
$$S_n = \frac{\sum(\prod f(a_n;a_{n-1},b_{n-1},\dots,a_1,b_1))}{\sum(\prod f(b_n;a_{n-1},b_{n-1},\dots,a_1,b_1)))+\sum(\prod g(a_{n-1},b_{n-1},\dots,a_1,b_1))}$$
Where I intentionally used the same $f$ twice, since the beginning of the denominator is exactly the same as swapping $a_n$ in the numerator for $b_n$.
If we were to obtain such a formula, it wouldn't be difficult to prove its validity by induction. So any help would be appreciated!
Comment: There is no *useful* closed formula like this. To compute $S_n$ using the recursion you only require $n$ additions and $n$ divisions. A closed formula like the one you seek will be much more complicated and require many many more additions and multiplications/divisions.
Comment: Closely related: [Generalized Continued Fraction - Wikipedia](https://en.wikipedia.org/wiki/Generalized_continued_fraction)
Answer: What you have is an iterated composition according to the terminology of Dixon J. Jones, A chronology of continued square roots and other continued compositions, through the year 2016 in contrast to a similar continued composition which would be a continued fraction in this case. The Wikipedia article
Continued fraction has some indication of using products of $2\times 2$ matrices to compute convergents. This seems to be the best way to proceed.
Define the sequence of matrices
$$  M_n := \begin{bmatrix} 0 & 1 \\ a_n & b_n  \end{bmatrix}. \tag{1}$$
and the sequence of matrix products
$$  P_n := \begin{bmatrix} u_n & v_n \end{bmatrix} :=
 \begin{bmatrix} 0 & 1 \end{bmatrix} \; \prod_{k=1}^n M_k
 . \tag{2}$$
with $\ S_n = u_n/v_n\ $ which is the closed formula you wanted.
By the way, if the we use the matrix transpose $\ M_n^\top\ $  of the $\ M_n\ $ and multiply on the right with $\ [^{0}_{1}],\ $
then we get continued fractions instead of iterated fractions.
An alternative approach comes from the Wikipedia article Continuant. Given the sequence of tridiagonal determinants
$$ d_0 := 1, \; d_1 := \mid b_1\mid, \;
   d_2 := \begin{vmatrix} b_1 & -a_1 \\ 1 & b_2 \end{vmatrix}, \;
   d_3 := \begin{vmatrix} b_1 & -a_1 & 0 \\ 1 & b_2 & -a_2 \\ 0 & 1 & b_3 \end{vmatrix},\  \dots, \tag{3} $$
then the sequence $\ S_n = a_n\  d_{n-1}/d_n.\ $
The determinants satisfy the recursion equation
$$ d_{n+1} = b_{n+1}\ d_n + a_n\ d_{n-1}. \tag{4} $$


For what values of x, would tan x lie in the range from (-1,1)?

Question: Please tell me a method to find this. And how do I check the range for tan function if I am given a random interval for the angle.
Comment: There are infinite, disjoint intervals that fulfill the condition. Do you want this or some limited interval?
Answer: Hints:
$$-1<\tan x<1\iff -\frac\pi4+k\pi<x<\frac\pi4+k\pi\;,\;\;k\in\Bbb Z$$
Try to make sense of the above...
Answer: $$tan(x) = \frac{\sin(x)}{\cos(x)} \quad \forall x \in \mathbb R \setminus\{\pi/2+k\pi, k\in \mathbb Z\}$$
$$-1<\tan x<1\iff \lvert\frac{\sin(x)}{\cos(x)}\rvert < 1 \iff \lvert \sin(x) \rvert < \lvert \cos(x) \rvert  $$
Looking at the trigonometric circle then gives you the rest... i.e.
$$\lvert \sin(x) \rvert < \lvert \cos(x) \rvert  \iff -\pi/4+k\pi<x<\pi/4+k\pi \quad \forall k \in \mathbb Z$$
As for your second question, given an interval $[x1,x2]$
$$ \exists k \in \mathbb Z \quad \vert \quad x1 < \pi/2+k\pi < x2 \implies range = ]-\infty,+\infty[$$
$$\not \exists k \in \mathbb Z \quad \vert \quad x1 < \pi/2+k\pi < x2 \implies range = [\arctan(x1),\arctan(x2)]$$


Confused about switching Lebesgue integrals for Riemann integrals

Question: Hi I have been attempting given in the link below. I am confused about the argument used to show the function is not Lebesgue integrable.
This question
What each person has used to answer is the fact that $ \displaystyle\int_0^{\infty} \big|\frac{sin(x)}{x}\big|\; dx$ (Riemann integral!!) does not converge implies $\displaystyle\frac{sin(x)}{x}$ is not Lebesgue integrable. I have not seen any theorems that say you can do this. I have a theorem in my notes which says;
If $f$ and $|f|$ are integrable on an interval I (bounded or unbounded)in the improper Riemann sense, then it is Lebesgue integrable on I and the integrals coincide.
This theorem is not iff and so this argument makes no sense to me, its like saying if we have A implies B then not A implies not B. I have looked around for other theorems but they are all in this direction. Please can someone explain rigorously why the above argument works and in general when you can switch $d\lambda(x)$ for $dx$ because people just seem to do it whenever they want and its confusing. Thanks
Comment: You take then on compacts of the shape $[0, a]$ and you take $a$ to infinity. The $R-\int$ and the $L-\int$ on such compacts of $(sinc(x))^+$ coincide. So in the limit, they also coincide.
Comment: $L_1$ is the space of all Lebesgue integrable functions. $sinc$ does not belong in the $L_1$ space, therefore it is not integrable. For example here: http://press.princeton.edu/chapters/s9627.pdf (pdf) it is defined as an *iif*. Am I missing something?
Comment: do you mean sin(x) does not belong to $L_1$ and so sin(x)/x does not belong to it? If so why is that true?
Comment: On what page is it defined as an iff?
Comment: On page 2: *When $p=1$ ...*. The Lebesgue integral of a function is defined as the difference of the Lebesgue integral of its positive part minus $\int$ of its negative part (both must be $<\infty$). Since $\int (sinc(x))^+ \,dx = +\infty$ then $sinc$ is not in $L_1$ therefore not L-integrable. $sinc(x) = sin(x)/x$.
Comment: Yes but you have just evaluated $sinc(x)$ as a **Riemann** integral, why can you just do that, the condition is that $\int(sinc(x))^+ d\lambda(x)<\infty$ notice the $d\lambda(x)$ not $dx$. do you take it as an integral on a bounded interval then let one end tend to infinity?
Comment: Ok thank you, that makes sense now
Answer: If the Lebesgue integral exists, it must be finite. That is, we need $$\int_0^{\infty}\frac{|\sin x|}{x}<\infty$$ By Lebesgue's Monotone Convergence Theorem, we have that $$\int_0^{\infty}\frac{|\sin x|}{x}=\sum_{n=1}^{\infty}\int_{(n-1)\pi}^{n \pi}\frac{|\sin x|}{x}\ dx\geq \sum_{n=1}^{\infty}\frac{1}{n\pi}\int_0^{\pi}|\sin x|\ dx=\infty$$
Hence the Lebesgue integral is not finite and so it does not exist.
Remark: We have equality on the first step because if $f:[a,b]\to\mathbb{R}$ is a bounded Riemann Integrable function, then $f$ is also Lebesgue measurable on $[a,b]$ and the two integrals agree.
Comment: I see now, thank you. The way he says not Lebesgue integrable because $\displaystyle\int_0^{\infty} \frac{|sin(x)|}{x} \; dx$ does not converge is incorrect and misleading. It should be $d\lambda(x)$.


How to get birthday via Facebook API?

Question: I am setting up a Facebook login, and am successfully getting things like first_name, email, etc. However, I cannot seem to figure out how to get birthday. If I call for birthday as below, nothing returns.
FB.api('/me', {fields: 'birthday'}, function(response) {
  console.log(JSON.stringify(response));
})

If I call user_birthday as below, I get this error: "error":{"message":"(#100) Tried accessing nonexisting field (user_birthday)
FB.api('/me', {fields: 'user_birthday'}, function(response) {
  console.log(JSON.stringify(response));
})

How do I do this?
Comment: Are you sure that every user has entered a birthday ?
Comment: Does `birthday_date` work?
Answer: Since you did not post your login code and you did not mention permissions, i assume you forgot one important thing: Authorizing with the user_birthday permission.
FB.login(function(response) {
    if (response.authResponse) {
        //user authorized the app
    }
}, {scope: 'user_birthday', return_scopes: true});

user_birthday is the permission, birthday is the name of the field. If it still doesn´t work, then there is most likely no birthday set. Not sure if it is required.
For example: http://www.devils-heaven.com/facebook-javascript-sdk-login/

How to get birthday via Facebook API?


Drawing a user interface based on preferences

Question: I want to use the built-in preference system for my xulrunner (Firefox) application.  But I can't figure out how to easily drive the user interface based on preferences.
The user can specify a list of home pages, and each home page will show up in a different tab.  Because the tabs are in the presentation layer, I'd like to create them using a template in the xul code.  Is this possible?
I haven't seen a way to do this with xul templates.  Is there an alternative templating system that would allow me to change the UI based on user preferences?
Answer: No, templating in XUL is not powerful enough, so you're stuck with writing JavaScript code that reads the preferences and opens the needed tabs.
Answer:
XML.prototype.function::domNode = function domNode() {
    function addPrefix(prefix, name) {
        if (typeof(prefix) == "undefined" || prefix == null || prefix == "") {
            return name;
        } else {
            return prefix + ":" + name;
        }
    }

    function recurse(xml) {
        var domNode = document.createElementNS(xml.namespace().uri, addPrefix(xml.namespace().prefix, xml.localName()));

        for each (let attr in xml.@*::*) {
            let attrNode = document.createAttributeNS(attr.namespace().uri, addPrefix(attr.namespace().prefix, attr.localName()));
            attrNode.nodeValue = attr;
            domNode.setAttributeNode(attrNode);
        }
        if (xml.hasComplexContent()) {
            for each (let node in xml.*) {
                domNode.appendChild(recurse(node));
            }
        } else if (xml.hasSimpleContent()) {
            domNode.appendChild(document.createTextNode(xml));
        }
        return domNode;
    }

    return recurse(this);
};

var name = "example"
var xml = {name};

document.querySelector("#example-statusbar-panel").appendChild(xml.domNode());

works as a charm, there's some minor glitches with namespaces though.
You could always convert dom back to XML with
var str = serializer.serializeToString( xml.domNode() );


How can I access the paragraph fields from my node via Tokens?

Question: Token Version: 8.x-1.7
Paragraphs Version: 8.x-1.12
I have one main node. In this main node I have referenced another sub-node. This sub-node has two fields with paragraphs. Each of these paragraphs consists of further text fields.
I would like to access these fields in the pargraphs by token. Unfortunately, I cannot find a suitable token for this. Neither in my token browser nor under /admin/help/token .
The only token with which I can access the field is the following:
[node:field_agent_reference:entity:field_gratification_for_agents].
But unfortunately this only gives me the whole content of the paragraph and not the fields individually. What am I doing wrong?
All other tokens that start with paragraphs, such as:
[paragraph:field_agent:entity:field_gratification_fur_agents]
[paragraph:field_agent:entity:field_bonus_number_or_percent]
[paragraph:field_percentage_media]
[paragraph:field_percentage_media:value]
do not function for me.
Thanks a lot
Bavra
Answer: The token browser stops spitting out chained suggestions after a sensible level of nesting - otherwise the memory use and (lack of) UI responsiveness could easily get out of hand. That doesn't mean that chaining stops, just the available hints.
You can keep right on going, e.g.
<code>[node:field_agent_reference:entity:field_gratification_for_agents:entity:field_foo:value]
</code>
Answer: Thank you for your feedback. So I have now tried the following, without result:
[node:field_agentur_reference:entity:field_gratifikation_fur_agenten:entity:0:field_auszahlung:value]
[node:field_agentur_reference:entity:field_gratifikation_fur_agenten:entity:0:field_auszahlung]
[node:field_agentur_reference:entity:field_gratifikation_fur_agenten:entity:field_auszahlung:value]
[node:field_agentur_reference:entity:field_gratifikation_fur_agenten:0:entity:field_auszahlung:value]
[node:field_agentur_reference:entity:field_gratifikation_fur_agenten:0:entity:field_auszahlung]
The machine name of the paragraph is:   gratifikation_fur_agenten
The machine name of the two fields in the paragraph is:
field_auszahlung
field_prozent
both from type number(integer)
Thnx
Answer: I would like to change the depth/recursion of the token browser for a moment. I know about the risk.
I have played with the following settings in the token.module, but nothing has happened yet:
<code>'token_types' => [],
  'global_types' => TRUE,
  'click_insert' => TRUE,
  'show_restricted' => TRUE,
  'show_nested' => TRUE,
  'recursion_limit' => 8,
  'text' => NULL,
  'options' => [],
</code>
Did I miss something?
Thank you and greetings
Bavra


Flyway (SpringBoot) migration with file in multiple directories skip version

Question: I am working on a SpringBoot application with Flyway. I have to update the database that already has those migration :

The migrations under common must be executed on different environements (Spring profiles loaded) while local and qa will have different data inserted into a H2 database.
I need to alter the table (adding and modifying columns) and then update the data inserted in V1_1 and V1_2. I tried MANY different approaches to avoid putting the ALTER TABLE sql command in the local and qa migration files. I would like to leaver the ALTER TABLE commands in the common folder, while in the local and qa folder only have the update commands. But all of them were in vain, the new migration I add in the local directory always gets executed before the one I add in the common repository :

Even with the naming scheme above, V1_4 gets executed before V1_3, causing an error because the new columns were not added yet. I know this is not the perfect naming scheme, I used it mostly for testing and expressing my point. But even while manually testing, flyway does not behave like I would expect (surely because of my misunderstaing). The app log clearly shows V1_3 not being executed :
2019-08-13 13:31:04.025  INFO 26508 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version 1.0 - schema
2019-08-13 13:31:04.076  INFO 26508 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version 1.1 - institutions
2019-08-13 13:31:04.092  INFO 26508 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version 1.2 - data
2019-08-13 13:31:04.476  INFO 26508 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version 1.4 - update data
2019-08-13 13:31:04.482 ERROR 26508 --- [           main] o.f.core.internal.command.DbMigrate      : Migration of schema "PUBLIC" to version 1.4 - update data failed! Please restore backups and roll back database and code!

I am using this propertiy : spring.flyway.locations=classpath:db/migration/common,classpath:db/migration/local
 in the environnement where the exception occurs.
What am I doing wrong ? I can't seem to find a lot of documentation on flyway migration with file in multiple directories. Unfortunatly, this is what I am stuck with and I cannot change the file structure since these decision are out of my hands.
Thanks in advance !
Comment: Your 1_3 version is lower case. Most probably it's not seen by Flyway
Answer: When you provide a location for your migration, flyway looks for .sql files under that folder and subfolders. So if you have V1.1 and V1.4 in Local and V1.3 in Common, flyway will treat Local as the migration folder and execute in the order V1.1 and V1.4, it won't go to common unless you provide root dir as your flyway location. In your case you should give db.migration as your location.


Visual Studio 2010 bug in using controls!

Question: I create a C# windows form application in visual studio 2010. I create some controls and darg them into my main form. Every time I change the controls, building of the project faild because the exe (output) file is locked (there is no any syntax error).
After above error I have to close VS and reopen the project.
My question is I make mistake or visual studio has a bug in this situation?
Thanks.
Comment: Watch out for circular dependencies.  Build + Clean and verify that it still builds.
Answer: Is the executable running from the Debug or Release directory? You can't recompile it if the output is running, then Visual Studio won't be able to replace it.
Comment: When the app is running, you are right. but the app is not running.


Erro ao rodar programa

Question: #include<stdio.h>
#include<math.h>

int main ( void ){
int x;
int i;
printf("Input the number (Table to be calculated) : ");
scanf("%d", x);

for( i = 1; i <= 10; i++){

    printf("%d x %d = %d", x, i, x*i);
}
return 0;

}

Gostaria de saber o motivo do erro?
já tentei criando uma variavel pra segurar o valor de x*i dentro do loop, mas ainda assim não funciona, depois que dou o primeiro input visto na tela, o Windows identifica um problema...
Comment: Falta o `&` no `scanf()`. Precisa informar qual endereço de memória receberá o valor inteiro. Neste caso, o endereço da variável `x`. Então passe `&x`.
Answer: Após o primeiro parâmetro, a função scanf espera receber uma referência à variável que pretende guardar o valor da entrada:
scanf("%d", &x);

Espero ter ajudado.
Answer: além do "&" em "scanf" como já foi mencionado, você colocou na função main o void e no final do código "return 0", e isso está errado pois void não retorna nada.
Comment: `int main` significa que o retorno é `int`, e não `void`.

Erro ao rodar programa


How do I change a theme based on the URL?

Question: I have a Drupal instance running on example.org. Which has a theme X installed and activated. Now for a limited period an event is supposed to be held on the site for which a special section has been "carved out." All the things related to that event will go to example.org/event2011.
I want to have a different theme to be shown whenever a page under this section is viewed (e.g. http://example.org/event2011/about, http://example.org/event2011/node/123). How do I do that?
I have gone through many modules, but none of them is supporting Drupal 7. Preferably, I would like it to be done using modules and don't want to change anything my self at the code level.
Answer: Since the change is for a limited period of time, and implementing it isn't much difficult, I would suggest to create a custom module, or add the code to change the theme used for specific pages in an existing, suitable, custom module.
It is enough to implement hook_custom_theme(), for example using the following code.
function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'the theme to use for that page';
  }
}

If the theme must be changed for http://example.com/event2011, but not for http://example.com/event2011/node/123, code similar to the following one could be used.
function mymodule_custom_theme() {
  if (arg(0) == 'event2011' && !arg(1)) {
    return 'the theme to use for that page';
  }
}

As for using theme callbacks in a menu callback definition, the documentation says:

As a general rule, the use of theme callback functions should be limited to pages whose functionality is very closely tied to a particular theme, since they can only be overridden by modules which specifically target those pages in hook_menu_alter(). Modules implementing more generic theme switching functionality (for example, a module which allows the theme to be set dynamically based on the current user's role) should use hook_custom_theme() instead.
Comment: I would suggest the current_path() function
https://api.drupal.org/api/drupal/includes%21path.inc/function/current_path/7.x. You will have an easier "for" condition
Answer: A custom solution like the other comment suggests is probably best, but if you really want to use a module, your best bet is ThemeKey. As of 5/23/11, it has a stable release.
Answer: Alternatively you can use the new theme callback option of the menu system hook_menu_alter() as outlined below. p.s Checkout hook_menu() for more details on the theme callback
<?php
/**
* Implements hook_menu_alter().
*/
function mymodule_menu_alter(&$items) {
  // Set the theme callback function for all node pages. As per the
  // standard behavior for hook_menu() properties, this will be
  // inherited by all paths underneath node/%node as well, unless
  // they define their own theme callback.
  $items['node/%node']['theme callback'] = 'mymodule_default_node_theme';

  // Set a different theme callback for node edit pages, and pass
  // along the node object to this function so we can make decisions
  // based on it.
  $items['node/%node/edit']['theme callback'] = 'mymodule_edit_node_theme';
  $items['node/%node/edit']['theme arguments'] = array(1);
}
/**
* Defaults to using the 'some_theme' theme for node pages.
*/
function mymodule_default_node_theme() {
  return 'some_theme';
}

/**
* For editing page nodes, uses the 'some_other_theme' theme.
*/
function mymodule_edit_node_theme($node) {
  return $node->type == 'page' ? 'some_other_theme' : mymodule_default_node_theme();
}
?>

Additionally there is also an example of using the more traditional hook_custom_theme()
<?php
/**
* Implements hook_custom_theme().
*/
function mymodule_custom_theme() {
  // check path using arg(0)
  // check $user
  // do whatever special checking you want and simply return theme key (name of theme folder most of the time)
    return 'special_theme';
  }
}
?>

Taken from: http://drupal.org/node/224333#custom_theme
Answer: You can simply use Context and use the theme to get applied when the path is /event2011/
you can simple set the path in condition of cotext and change the theme in the action of the content. This was you can very easily switch between themes on a site based on URL. Even works for mobiles ;)
Comment: the theme action passes custom variables to the theme, it doesn't actually change it
Answer: Using ThemeKey is simple and it's the most popular and powerful module so far (with support for 8.x) for theme switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. Beside the standard features ThemeKey automatically extends it's features of many contrib modules and has modules extending it.
Usage (7.x)
After enabling module, go to admin/config/user-interface/themekey. There are many options for switching the theme, but probably you would be interested with path:node_alias, so set the value as you want like you say /my_url and then select the theme you want to enable at this url. You can also use wildcards such as web/* or /^web/.*.
Check: How Load a Theme For Path
Advanced usage
ThemeKey 7.x contains an optional module called ThemeKey Example to demonstrate developers how to extend ThemeKey.
Help (7.x)
Check out video tutorial by Mustardseed (7.x).
More help on that topic can be found at /admin/help/themekey.
Also check other SE questions related to themekey.

Alternatively there is also Switchtheme (7.x) which adds a block to allow users to switch between enabled themes.
Answer: When using URL aliases or the Pathauto module, be aware of the subtleties and differences when using components of the current Drupal path.
There are situations where you may not want to use arg(). In fact, the Drupal API documentation actually suggests avoiding use of this function where possible, as resulting code is hard to read.
Consider the following example, as proposed by kiamlaluno:
function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'custom_theme_machine_name';
  }
}

In Drupal 7, if a node has an alias of event2011, using arg(0) will return node as the first URL component, as opposed to the alias.
print_r(arg(0));

Array
(
    [0] => node
    [1] => 150
)

Instead, if you need to work with an alias there are several ways to get the current URL in Drupal, including menu_get_object(), current_path(), request_path() and others.
Here's a re-worked example that uses an alias as a trigger for switching the theme:
function mymodule_custom_theme() {
  $current_page_path = explode('/', request_path());

  if ($current_page_path[0] == 'event2011') {
    return 'custom_theme_machine_name';
  }
}

Answer: How to switch theme depending on user role:
Create a custom module and copy & paste the following:
<?php
/**
 * Implementation of hook_init().
 */
function mymodule_init() {
  global $custom_theme, $user;
  if (in_array('my special role', $user->roles)) {
    $custom_theme = 'mytheme';
  }
}
?>

You have to replace:
mymodule => with your module name
my special role => with the name of the role that your users will need to have in order for them to see a different theme.
mytheme => with the name of the theme that you want to switch to
Answer: You could use the Page Theme module to achieve exactly that

The Page Theme module is a simple and easy module to use which allows
  to use different themes than the site default on specific pages.
Features

Assign a theme to a single page or list of pages. (Set a page as a
  Drupal path)
Allow to use '*' character as a wildcard in Drupal paths.
Allow to arrange themes. (If pages are several defined, the first
  theme in the list will be used)
Allow to enable/disable a theme.
Drupal novice friendly.
Answer: If you want to use a theme that is different from the theme site default on content creating, editing, and viewing pages you can use
the Content Theme module.