How many 10-letter words are there in which each of the letters e,n,r,s occur at most once?

Question: Solve with a generating function. My solution was
$$g(x)=\left(\frac{x^0}{0!} + \frac{x^1}{1!}\right)^4 \left(\frac{x^0}{0!} + \frac{x^1}{1!} + \frac{x^2}{2!} + ... \right)^{26-4}$$
$$g(x) = (1 + x)^4e^{22x}$$
$$g(x) =\left( \binom{4}{0}x^0 + ... +\binom{4}{r}x^r... + \binom{4}{4}x^4\right)\sum\nolimits 22^r \frac{x^r}{r!}$$
Then we are trying to find the coefficient of the tenth term I denote as $a_{10}$
$$g(x) = h(x)f(x)$$ where $h(x) = (1 +x)^4$ and $f(x) = e^{22x}$
$$g_{10} =h_0f_{10} +  h_1f_{9} +  h_2f_{8} +  h_3f_{7} +  h_4f_{6} $$
$$ = \binom{4}{0}22^{10} +  \binom{4}{1}22^{9} +  \binom{4}{2}22^{8} +  \binom{4}{3}22^{7} +  \binom{4}{4}22^{6} $$
Now this is not correct and instead is supposes to be:
$$ = \binom{4}{0}\frac{10!}{10!}22^{10} +  \binom{4}{1}\frac{10!}{9!}22^{9} +  \binom{4}{2}\frac{10!}{8!}22^{8} +  \binom{4}{3}\frac{10!}{7!}22^{7} +  \binom{4}{4}\frac{10!}{6!}22^{6} $$
1) The correct expression seems to include  $\binom{4}{r}\frac{10!}{(10-r)!}$ for evaluating the coefficients of $h(x)$ but why is this?
2) If this if correct, why are we using two different values for $n$? We make $n=4$ for evaluating the coefficient of $(1+x)^4$  but then somehow incorporate $n=10$ for $P(n,r)$
Comment: It is not clear to me what you mean by $h(x)$ and $f(x)$
Comment: a quick note you are missing the factor $\frac{1}{n!}$ for $c_n$ coefficients.
Answer: In your computation you are missing the factor $\frac{1}{i!}$ for $f_i$ coefficients.
Fixing this, what you should be looking for is: $P(n=10,r=4)$ (this should answer your second question)that is:
$$\sum_{i=0}^{r}h_i f_{n-i}x^n= \sum_{i=0}^{r} \binom{r}{i} \frac{22^{n-i}}{(n-i)!}x^n$$
substituting for $r=4$ and $n=10$ you will get the expected result you mentioned except for the $10!$ factor, which is the result of the permutation of 10 letters.
So the final answer would be:
$$ = 10!\bigg( \binom{4}{0}\frac{1}{10!}22^{10} +  \binom{4}{1}\frac{1}{9!}22^{9} +  \binom{4}{2}\frac{1}{8!}22^{8} +  \binom{4}{3}\frac{1}{7!}22^{7} +  \binom{4}{4}\frac{1}{6!}22^{6})\bigg) $$
Comment: The only reason I am using the $\binom{n}{r}$ coefficients is because those are the coefficients of $(1+x)^n$. Where is  $\sum_{i=0}^{r} \binom{r}{i} \frac{22^{n-i}}{(n-i)!}x^n$ coming from?
Comment: you are basically multiplying two series f(x) and h(x) to get series g(x) and the way to find $g_n$ coefficients is $g_n=\sum_{i=0}^{n} h_i f_{n-i}$ that's how you get that term. see this [link](http://math.stackexchange.com/questions/106649/multiplying-taylor-series-and-composition)
Comment: It's just closed form of writing $g_{10} =h_0f_{10} +  h_1f_{9} +  h_2f_{8} +  h_3f_{7} +  h_4f_{6} $ that you have in your question.
Answer: Hint: does $f(x)*h(x)$ give you the coefficient of $\frac{x^{10}}{10!}$?
Consider $f_1h_9$, if you perform the product without much consideration, you get
$$ {4 \choose 1} x^1 * 22^9 * \frac{x^9}{9!} = {4 \choose 1} * 22^9 \frac{x^{10}}{9!} $$
but you want $10!$ in the denominator.
So you need to multiply with $\frac{10}{10}$ to get $${4 \choose 1} * 22^9 * \frac{10}{10} * \frac{x^{10}}{9!} = {4 \choose 1} * 22^9 * 10 * \frac{x^{10}}{10!}$$


prove that the fucntion f(x)=(1-x)/(1+x) is uniformly is continuous [0,infinity).

Question: let ε>0  there is δ>0 such that |f(x)-f(y)|<ε
let |y-x|<δ and |1-x|=2 and |1-y|=2 and let δ<2ε
|(1-x)/(1+x)-(1-y)/(1-y)|<2(y-x)/(1+x)(1+y)|=δ/2<ε
is this the way to do it?
Comment: Also check the M.SE guidelines on formatting equations here : http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: Your steps are correct in showing that
$$|f(x) - f(y)| = \left|\frac{2(y-x)}{(1+x)(1+y)}\right|.$$
You do not want to restrict $x$ and $y$ by taking $|1-x|= 2$ and $|1-y| = 2.$
Note that for all $x,y \geqslant 0$
$$|f(x) - f(y)| = \frac{2|y-x|}{(1+x)(1+y)}\leqslant 2|y-x|.$$
Hence, for all $x,y \in [0,\infty)$ with $|x-y| < \delta = \epsilon/2$ , then we have $|f(x) - f(y)| < \epsilon$.
However, the function $f$ is not uniformly continuous on $(-1,\infty)$.
Consider the sequences $x_n = -1+1/n$ and $y_n = -1 + 1/2n$.  Then as $n \to \infty,$
$$|x_n - y_n| = \frac1{2n} \to 0,$$
but
$$|f(x_n)-f(y_n)| = \frac{2 \frac1{2n}}{\frac1{2n^2}}= \frac{n}{2} \to \infty.$$
Comment: ok thank you another question is that this function is not uniformly continuous on (-1,infinity).how do i do this ? is it the same way .wat would be different?
Comment: You're welcome -- I'll add to the answer.
Comment: In that case I show above there are sequences $(x_n)$ and $(y_n)$ in $(-1,\infty)$ that get arbitrarily close but for which $|f(x_n)-f(y_n)|$ gets arbitrarily large.
Comment: Your function goes to $\infty$ near $-1$. Write your uniform continuity inequality between $0$ and $x \to -1$ and you will get a contradiction
Answer: You're in a particular case where $||f'||_{\infty}$ is bounded on your domain (easy to check).
This implies that $f$ is Lipschitz on the domain (with $||f'||_{\infty}$ being a Lipschitz factor)
Which in turns implies that $f$ is uniform. continuous (actually you can skip the Lipschitz part and just use the mean value theorem).


.each being used in Rails app when only one result should exist

Question: I don't understand why "each" appears in the third line because I think there is no other page which meet the condition
:member_id => session[:user_id], :friend_id => params[:id]

Could you tell me why?
  def friend
    if Friend.where(:member_id => session[:user_id], :friend_id => params[:id]).exists? then
      Friend.where(:member_id => session[:user_id], :friend_id => params[:id]).each do |f|
       f.destroy
       end
    else
       Friend.new({:member_id => session[:user_id], :friend_id =>params[:id].to_i}).save
    end
    redirect_to :action => 'show', :id => params[:id]
  end

Comment: I would have refactored that to show the correct technique, and make it much simpler, but I can't figure out what it does. Why are you destroying a friend, if found, and otherwise creating a new friend but then throwing that one away?
Comment: Mr.Phlip, this code comes from the sample code from my text, which has a system that you can be friends with someone when you push a link and you can destroy the relationship when you push the link again.
Answer: The Active Record finder method where returns an array, even if there is only one element in it, so your either have to iterate through the array with each or if you know only one will returned, you could do something like use the first method, an example using the first method is:
def friend
  if Friend.where(:member_id => session[:user_id], :friend_id => params[:id]).exists?
    Friend.where(:member_id => session[:user_id], :friend_id => params[:id]).first.destroy
  else
    Friend.new({:member_id => session[:user_id], :friend_id =>params[:id].to_i}).save
  end
  redirect_to :action => 'show', :id => params[:id]
end

Friend.where(:member_id => session[:user_id], :friend_id => params[:id]).first returns the first (and if you're correct), only object
Hope this helps
Comment: DRYing that code up would make the actual control flow more obvious. Just sayin'...
Answer: I think you are right the .each is not needed. My Rails 2.3 provides .destroy_all, which returns what it destroyed:
def friend
  friend_params = { :member_id => session[:user_id], :friend_id => params[:id] }

  if Friend.destroy_all(friend_params).empty?
    Friend.new(friend_params).save
  end

  redirect_to :action => 'show', :id => params[:id]
end

So if you couldn't find a friend to destroy, add the friend.


Run totally silent rsync?

Question: I have a cronjob that runs hourly, and is totally silent unless something goes wrong. Well ... almost ...
A part of the job is
rsync --del -Cacqrz public/. firstname.lastname@example.com:/target/path

This always prints "logged in". How can I make it stop? (Short of 'grep -v' ;-)
I don't get the "logged in" message if I do things like
ssh email@example.com ls

The transport is, of course, ssh (using keys).
Source host is either OSX or Ubuntu (tried both, same behavior).
Target host is Linux of some flavor.
Comment: You can change the default verbosity of ssh in ~/.ssh/config or globally in ssh_config (location varies with distro).
Answer: quiet option should do that:
-q, --quiet                 suppress non-error messages
Comment: I'm using the rsync "-q", which successfully stifles a lot of blather, but it's not stopping this one message (which does not look like a problem to me). I think the un-stifled message comes from ssh/scp, but I don't have direct access to that command line. So I don't see how your suggestion helps.
Comment: You can modify ssh options:  `rsync -e 'ssh -q'` will stop ssh from outputting the ssh banner, for example.
Answer: You can redirect stdout and stderr to /dev/null with something like:
<command> 2>&1 >/dev/null

Comment: Error Checking? ***AIN'T NOBODY GOT TIME FOR THAT!***
Comment: @voretaq7 Meh, it's friday. I'm drinking beer. Can't think about such things. :)
Comment: ...and then check the return code from `rsync` (`$?`) -- if it's non-zero something went wrong and you have to handle that error gracefully.

Run totally silent rsync?


Counting numbers that have three different prime factors

Question: There are 1000 numbers in numbers.txt, 2 to 9 digits each, each in a seperate line. The exercise is tocount how many numbers there are, that fullfill the condition: when factorized, this number has exactly 3 different prime factors, they can occur several times and they all are even numbers.
for example
 105 - factors: 3, 5 ,7  - YES,
1287 - factors: 3, 3, 11, 13 - YES,
1157625 - factors: 3,3,3,5,5,5,7,7,7 - YES,
55 - factors: 5, 11 - NO.
#include <iostream>
#include <fstream>
using namespace std;
int number, threefnumbers=0;
int main()
{
  ifstream file("numbers.txt");
  ofstream outputf("results.txt");
  int count_factors;
  while (file >> number)
  {
    count_factors=0;
    int factor=3;
    if (number%2!=0)
    {
       while (number>1)
       {
        if (number%factor==0)
          count_factors++;
        while (number%factor==0)
        {
          number=number/factor;
        }
        factor+=2;
       }
       if (count_factors==3) threefnumbers++;
     }
  }

  outputf << "59.1) " << endl << threefnumbers;

  file.close();
  outputf.close();
  return 0;
}

I know from the numbers.txt, that there are many numbers that fulfill the condition, but the program returns only 1. Why so?
Comment: "they all are even numbers". None of your example numbers is even!
Comment: @A.Wabbi 2 is a prime number
Comment: Impossible to have even numbers. Primes are always odd.
Comment: Off topic: Save yourself a lot of computation and look up the Sieve of Eratosthenes. Cache and reuse the results.
Comment: @A.Wabbi The *factors* will be primes (and thus, save for 2, be odd); the *numbers* being tested and factored can certainly be even (or odd).
Comment: If numbers are supposed to be even, why do you have if (number%2!=0)?
Comment: I just tried your code and it looks like it works. Can you provide an example where it doesn't?
Comment: God, it suppose to be "They all are odd numbers". I wanted to count odd prime factors, that's why i skip the 2s. Terrible mistake.
Answer: Your code ignores the fact that 2 is a prime number.  You need to check if the number read in can be reduced by 2.  You could do that with something that look like:
while(read number)
{
    int factor_count = 0;
    // check 2 by itself
    if (number % 2 == 0)
    {
        factor_count++;
        while(number % 2 == 0)
            number /= 2;
    }
    for (int factor = 3; factor < number; factor += 2)
    {
        if (number % factor == 0)
        {
            factor_count++;
            while(number % factor == 0)
                number /= factor;
        }
    }
    if(factor_count == 3)
        do something
}

This entire thing could be made more efficient by making a list of prime numbers that goes up to the max number possible in the file which in this case would be 999,999,999.  Then you can just iterate through that prime number list until you run out of prime factors.  That would look something like
std::vector<int> primes = get_prime_list(999999999);
// returns a list of all prime numbers less than the number passed in.
// leaving it to you to implement but a Sieve of Eratosthenes should work well
while(read number)
{
    int factor_count = 0;
    for(auto e : primes)
    {
        if (number % e == 0)
        {
            factor_count++;
            while(number % e == 0)
                number /= e;
        }
        if (number == 1) // number is fully factorized
            break;
    }
    if(factor_count == 3)
        do something
}


Record streaming audio to FLAC format with vlc

Question: I have a question, I am trying to record audio from a radio stream and extract the audio in FLAC format with the following characteristics:
Channel: Mono
Sample rate: 16000
Bite rate: 320 or 128
I have the following vlc expression that I am using, does it correspond to my requirements above? And am I using the correct Audio codecs and Muxers?
"--sout=#transcode{acodec=flac,ab=320,channels=1,samplerate=16000}:std{access=file,mux=flac,dst='example.flac'}

Answer: You are using the correct audio codec acodec=flac but the mux should either be raw or ogg (mux=raw or mux=ogg). flac is the accepted audio codec for ogg container format and is thus used with it mostly.
For more details, look at this example:
Extracting audio in FLAC format
And the supported VLC Muxers


Reference request: Conditional posterior for bayesian hierarchical linear regression model

Question: I am searching for a reference computing the conditional posterior distribution of a bayesian hierarchical linear regression model of the standard form:
$$y\sim N(X\beta,\sigma I)\\
\sigma^2 \sim IG(v_1,v_2) \\
\beta|\mu,\sigma^2 \sim N(\mu,\Lambda_0 ^{-1})\\
\mu \sim N(\mu_0,\Lambda_1 ^{-1})
$$
In my perception this model is a standard example on how to work with hierarchical models, however, I failed in finding one source that gives me the conditional posterior distributions such that I can set up a Gibbs sampler. Each and every snippet summarizing this computation is welcome, I would also be happy to create this computation in this post in order to make it available easier. (Source code of the Gibbs sampler is also appreciated.)
Answer: I just realized, that ** Markov Chain Monte Carlo: Stochastic Simulation for Bayesian Inference (Texts in Statistical Science) ** provides the condtitional posteriors.


Quicksort em ordem crescente em Python

Question: Preciso ordenar a quantidade de vezes que as  palavras se repetem no arquivo txt, mas sempre que rodo o código ele printa em ordem decrescente.
Código abaixo:
from collections import Counter

with open('/Users/DIGITAL/Desktop/Python/teste.txt') as f:
    ocorrencias = Counter(f.read().split())
print(ocorrencias)

def quicksort(ocorrencias):
    if len (lista) <= 1:
        return lista
    pivo = lista[0]
    iguais = [x for x in lista if x == pivo]
    menores =[ x for x in lista if x < pivo]
    maiores = [x for x in lista if x > pivo]
    return quicksort(menores)+iguais+quicksort(maiores)
    print(quicksort(ocorrencias))

Comment: Precisa obrigatoriamente ser Quicksort?

Ou você simplesmente quer quanto cada palavra aparece? Se for existe um meio melhor de resolver.
Comment: Tem que ser Quicksort. Eu já consegui contar a quantidade de repetições, mas o programa printa em ordem decrescente. Preciso que ele printe em ordem crescente.
Comment: Você está guardando tudo em uma lista?
Comment: Não. Tá num arquivo txt
Answer: Dicionários não possuem ordenação. A função collections.Counter() retorna um dicionário.
O segredo para se ordenar dicionarios está em convertê-los para uma lista de tuplas para então ordená-las.
Com uma pequena modificação na função de quicksort da sua pergunta, é possível trabalhar com a ordenação de uma lista de tuplas e parametrizar em qual ordem vai ocorrer o ordenamento da lista:
from collections import Counter

def quicksort( array, reverse=False ):
    if len(array) <= 1:
        return array
    ( _, pv ) = array[0]
    iguais = [ (k,v) for k,v in array if v == pv ]
    maiores = quicksort([ (k,v) for k,v in array if v > pv ],reverse)
    menores = quicksort([ (k,v) for k,v in array if v < pv ],reverse)
    if reverse == True:
        return maiores + iguais + menores
    else:
        return menores + iguais + maiores

def ordenar( dic, reverse=False ):
    return quicksort( [ (k,v) for k,v in dic.items() ], reverse );

with open('teste.txt') as f:
    palavras = Counter( f.read().split() )

print "Crescente:", ordenar( palavras, reverse=False )
print "Decrescente:", ordenar( palavras, reverse=True )

teste.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Saída:
Crescente: [('laborum.', 1), ('ad', 1), ('irure', 1), ('ea', 1), ('officia', 1),
            ('sunt', 1), ('eu', 1), ('sed', 1), ('elit,', 1), ('enim', 1),
            ('Duis', 1), ('et', 1), ('aliqua.', 1), ('labore', 1), ('incididunt', 1),
            ('reprehenderit', 1), ('est', 1), ('quis', 1), ('sit', 1),
            ('veniam,', 1), ('nostrud', 1), ('qui', 1), ('id', 1),
            ('consectetur', 1), ('aute', 1), ('consequat.', 1), ('mollit', 1),
            ('aliquip', 1), ('nulla', 1), ('Lorem', 1), ('do', 1), ('non', 1),
            ('commodo', 1), ('Ut', 1), ('sint', 1), ('velit', 1), ('cillum', 1),
            ('pariatur.', 1), ('ex', 1), ('esse', 1), ('proident,', 1), ('magna', 1),
            ('cupidatat', 1), ('ullamco', 1), ('deserunt', 1), ('ipsum', 1),
            ('amet,', 1), ('nisi', 1), ('fugiat', 1), ('occaecat', 1), ('minim', 1),
            ('culpa', 1), ('tempor', 1), ('laboris', 1), ('anim', 1),
            ('adipiscing', 1), ('Excepteur', 1), ('voluptate', 1), ('exercitation', 1),
            ('eiusmod', 1), ('dolore', 2), ('ut', 2), ('dolor', 2), ('in', 3)]

Decrescente: [('in', 3), ('dolore', 2), ('ut', 2), ('dolor', 2), ('laborum.', 1),
              ('ad', 1), ('irure', 1), ('ea', 1), ('officia', 1), ('sunt', 1),
              ('eu', 1), ('sed', 1), ('elit,', 1), ('enim', 1), ('Duis', 1),
              ('et', 1), ('aliqua.', 1), ('labore', 1), ('incididunt', 1),
              ('reprehenderit', 1), ('est', 1), ('quis', 1), ('sit', 1),
              ('veniam,', 1), ('nostrud', 1), ('qui', 1), ('id', 1),
              ('consectetur', 1), ('aute', 1), ('consequat.', 1), ('mollit', 1),
              ('aliquip', 1), ('nulla', 1), ('Lorem', 1), ('do', 1), ('non', 1),
              ('commodo', 1), ('Ut', 1), ('sint', 1), ('velit', 1), ('cillum', 1),
              ('pariatur.', 1), ('ex', 1), ('esse', 1), ('proident,', 1),
              ('magna', 1), ('cupidatat', 1), ('ullamco', 1), ('deserunt', 1),
              ('ipsum', 1), ('amet,', 1), ('nisi', 1), ('fugiat', 1), ('occaecat', 1),
              ('minim', 1), ('culpa', 1), ('tempor', 1), ('laboris', 1), ('anim', 1),
              ('adipiscing', 1), ('Excepteur', 1), ('voluptate', 1), ('exercitation', 1),
              ('eiusmod', 1)]

Quicksort em ordem crescente em Python


Sorting out the dates in chronological order

Question: Friends I am having a String that contains date-record
String date=10-Oct-2012 @12-Oct-2012 @$12-Oct-2012 @12-Oct-2012 @$12-Sept-2012 13:50@12-Oct-2012 13:50@$12-Feb-2012 13:50@12-Oct-2012 13:50@$

List<Date> myList=new ArrayList<Date>() ;

I need to compare the dates 10-Oct-2012,12-OCt-2012,12-Sept-2012,12-Feb-2012 ie every odd date such that I can arrange them in a chronological order.I am confused on this implementation, please provide me with guidance/hint to solve the problem.
In this case the solution after chronological order would be 12-Feb-2012 @12-Oct-2012 @12-Sept-2012  @12-Oct-2012  @$10-Oct-2012 @12-Oct-2012 @$12-Oct-2012 @12-Oct-2012
Friends,to solve the problem I have created a Hashmap where I am planning to save the first date as key and the entire String as value.
String[] tokens=date.split("\\$");
    demo[0]=demo[0].replaceAll("-", ".");
if(tokens.length>0)
        {
            for(int iTmp=tokens.length-1;iTmp>=0;iTmp--)
            {
                String []demo = tokens[iTmp].split("\\@");
                    demo[0] = demo[0].replace("Jan", "1")
                    .replace("Feb", "2").replace("March","3").replace("April","4").replace("May","5").replace("Jun","6").replace("July","7").replace("Aug","8")
                    .replace("Sept","9").replace("Oct","10").replace("Nov","11").replace("Dec","12");
                    demo[0]=demo[0]+" 00:05:00";
                    Date date1 = null;
                    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yy");

                    try {
                        date1 = (Date)formatter.parse(demo[0]);

                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    myList.add(date1);
                    System.out.println("ADDED DATE IS"+date1);
                    //System.out.println("KEY VALUE PAIRS  "+key+"  "+tokens[iTmp]);
                }
            }
            System.out.println("READING LISTs");
            for(int iTmp=0;iTmp<myList.size();iTmp++)
            {

                System.out.println(myList.get(iTmp));
            }
            Collections.sort(myList);
            System.out.println("After Sorting");
            for(int iTmp=0;iTmp<myList.size();iTmp++)
            {

                System.out.println(myList.get(iTmp));
                System.out.println();
            }

Comment: don't store/handle/work on dates as strings, to begin with.
Comment: Please find the updated question
Comment: ok. and what is the error now (also, i don't understand the list you wrote as what should be the actual result)
Comment: i don't see any hashmap, either
Comment: @njzk2 I have sorted the first date(half task is done.)Now, depending on that values,I need to updated the entire String
Comment: i don't understand, but i think you are not parsing the time
Comment: so, what "half the task" means, what is this entire string you are mentionning, and on what values does that depends ?
Comment: I am able to sort the FIrst date, just need to modify the entire String.
 Sun Feb 12 00:00:00 GMT+05:30 2012
 Wed Sep 12 00:00:00 GMT+05:30 2012
 Wed Oct 10 00:00:00 GMT+05:30 2012
 Fri Oct 12 00:00:00 GMT+05:30 2012
Comment: that looks sorted to me. what string do you need to modify ?
Comment: I need to modify the date String
Comment: why? how? from what value to what value? do you mean the representation? i don't see any UI in your code, so i don't know where you need to actually have a representation to you dates
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/17933/discussion-between-onkar-and-njzk2)
Answer: It sounds pretty simple to me:

Parse each value into a more suitable type (Calendar, Date, Joda Time's LocalDate)
Sort in natural order

(Using Joda Time is the preferred option here IMO, as neither Calendar nor Date really represent "just a date"; you'd have to put all values into the same time zone etc.)
I would definitely not recommend trying to compare them as strings. As usual, convert your data into the most appropriate type for the information it's trying to represent as early as possible - and convert it into serializing representations (e.g. for storage, propagation to a web service etc) as late as possible.
Comment: @onkar: Ideally, save your data in a more machine-friendly fashion, e.g. as ISO-8601 values. 12-Feb-2012 is culture-sensitive; 2012-02-12 is standardized (assuming a Gregorian calendar, admittedly...) As ever with software engineering, you need to break your task up: 1) read data from the text file; 2) parse the data into more useful values; 3) manipulate the data, e.g. sorting
Comment: everything @JonSkeet said plus a little hint, you can use Collections.sort() to sort the values for you.
Comment: Hey mate I am looking for a calender app where user is permitted to add a combination of entries. I am saving those entries(txt file) and reading them for history. Please help me in improving my approach
Comment: Ok mate. natural order means which sorting shall I work on ? Thanks a ton for your valuable guidance
Comment: Hey mate I have added my approach, please check it.
Comment: @onkar: Could you please stop with the "mate"? And no, there's no need to create a `HashMap`. Just create a list and call Collections.sort...
Comment: Oh.. Sorry. I have successfully sorted the first entry(Using collection) ? How do I override the old history ?
Comment: @onkar: Your updated question seems to be confused - you've posted incomplete code (no declaration of `myList`) which doesn't match the text (it's presumably a list, not a map now), you're ignoring parse failures (really bad idea), and you haven't said what the result is. It's not clear what you expect anyone to be able to do with your question in its current state.
Comment: @onkar: No, you haven't. Everything I complained about in the previous edit is still the case.
Comment: I am able to sort the FIrst date, just need to modify the entire String. Sun Feb 12 00:00:00 GMT+05:30 2012 Wed Sep 12 00:00:00 GMT+05:30 2012 Wed Oct 10 00:00:00 GMT+05:30 2012 Fri Oct 12 00:00:00 GMT+05:30 2012 –
Comment: @onkar: Sorry, you're really not making much sense to me. Please read http://tinyurl.com/so-hints and take the time to edit your question into a *good* question.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/17931/discussion-between-onkar-and-jon-skeet)
Answer: Split the string and then
You can use gregorian calender (built in)
or you can use the yoda-time library
i can't say more about the sorting though
Comment: I think it not `yoda-time` it is actually Joda Time.
Answer: If you are developing for Android (there is an Android tag on your question), then you should know about the Time structures and methods in the Android SDK.
If possible, try to use a string representation of your date/time stamp that itself can be sorted naturally, like the RFC 3339 format (which Android supports with built-in methods).  This will let you work more easily with string timestamps, and also give you a simple way to convert to a canonical or integer-type format if desired.


Catching and logging MVC4 message about "Minification failed. Returning unminified contents"

Question: There are a number of questions on StackOverflow that talk about getting the Minification failed. Returning unminified contents error from the MVC4 minification.
I'd like to know if there is a way to be notified about this error when it happens and to be able to log it.
It is nice that when there is an error the bundler returns the original contents so my site doesn't break, but I would like to know about these errors automatically rather than having to visit each css/js bundle url to see if there is an error.
Comment: @MikeSmithDev, what I meant was that was the minifier is nice enough  to return the original CSS when there is a syntax error, therefore, not breaking the site
Answer: So that logic is actually in the implementation of the default transforms that Script/StyleBundle are using.  If you want to catch those errors yourself, you can change the transforms on your bundles to something that surfaces those errors:
So to actually detect the errors, you would have to manually enumerate all of your bundles (to trigger them to get generated), and also be able to listen to errors that happened (so the GenerateErrorResponse equivalent below would need to report any errors to someplace that you would see)
Here's what JsMinify does in its process for reference:
    ///
    /// Transforms the bundle contents by applying javascript minification
    ///
    /// <param name="context">The <see cref="BundleContext"/> object that contains state for both the framework configuration and the HTTP request.</param>
    /// <param name="response">A <see cref="BundleResponse"/> object containing the bundle contents.</param>
    public virtual void Process(BundleContext context, BundleResponse response) {
        if (!context.EnableInstrumentation) {
            Minifier min = new Minifier();
            // NOTE: Eval immediate treatment is needed for WebUIValidation.js to work properly after minification
            // NOTE: CssMinify does not support important comments, so we are going to strip them in JS minification as well
            string minifiedJs = min.MinifyJavaScript(response.Content, new CodeSettings() { EvalTreatment = EvalTreatment.MakeImmediateSafe, PreserveImportantComments = false });
            if (min.ErrorList.Count > 0) {
                GenerateErrorResponse(response, min.ErrorList);
            }
            else {
                response.Content = minifiedJs;
            }
        }

        response.ContentType = JsContentType;
    }

Comment: I wish there was a setting to toggle whether or not errors are bubbled/exposed rather than rewriting code.  Is there another way to see the response content going out and look for the "Minification failed. Returning unminified contents." error msg?  I think Response.Filter might be able to do this.


Calculate $20^{1234567} \mod 251$

Question: I need to calculate the following
$$20^{1234567} \mod 251$$
I am struggling with that because $251$ is a prime number, so I can't simplify anything and I don't have a clue how to go on. Moreover how do I  figure out the period of $[20]_{251}$? Any suggestions, remarks, nudges in the right direction are very appreciated.
Answer: Hint: Use Fermat's Little Theorem to find the period of $[20]_{251}$. Then, use this to simplify $20^{1234567}$.
Comment: Then do some exponentiation by squaring.
Comment: ...and then you're left with $20^{67} \bmod 251$.
Comment: How does that help?
Comment: If you square 20 six times, then multiply by 400 and then by 20, taking the factor mod 251 each time, you will have calculated $20^{67}$ modulo 251.
Answer: If you do not know the little theorem, a painful but -I think- still plausible method is to observe that $2^{10} = 1024 \equiv 20$, and $10^3 = 1000 \equiv -4$. Then, we may proceed like this:
$20^{1234567} = 2^{1234567}10^{1234567} = 2^{123456\times 10 + 7}10^{411522\times 3 + 1} = 1280\times 1024^{123456}1000^{411522} \equiv 1280\times 20^{123456}4^{411522}$.
Observe that after one pass, we are still left with the powers of $2$ and the powers of $20$ that we can handle with the same equivalences above.
We still have to make some calculations obviously (divisions etc), but it is at least not as hopeless as before.

Calculate $20^{1234567} \mod 251$


Ada loop stops after first input

Question: Hi I am currently writing a program that reads inputs from a file and determines whether or not the number is neither prime nor composite, is composite, or prime. Basically my problem is that I can not get my program to continue it stops after one input, even though I have more numbers in my file that need to be evaluated. Here is my code:
WITH Ada.Text_IO, Ada.Integer_Text_IO;
USE Ada.Text_IO, Ada.Integer_Text_IO;

PROCEDURE TestPrime IS
   PACKAGE Boolean_Io IS NEW Ada.Text_Io.Enumeration_Io(Boolean);
   USE Boolean_Io;

   N       : Integer;
   X       : Natural   := 2;
   S       : Integer;
   IsPrime : Boolean   := True;
   C       : Character;
BEGIN
   WHILE NOT End_Of_File LOOP
      Excep:
         BEGIN
      Get(N);
      IF N = 0 OR N = 1 THEN
         Put_Line(N'Img & " is neither prime nor composite");
      END IF;
      LOOP
         S := N mod X;
         IF S = 0 THEN
            IsPrime := False;
         END IF;
         EXIT WHEN X = N - 1;
         X := X + 1;
      END LOOP;
      IF IsPrime = True THEN
         Put_Line(N'Img & " is prime");
      ELSE
         Put_Line(N'Img & " is composite");
      END IF;
       EXCEPTION
           WHEN Data_Error =>
              Put_Line("Data error: You must enter a number!!");
              Get(C);
       END Excep;

   END LOOP;
END TestPrime;

I am just asking where my program is getting stuck and why it is happening. Any help will be greatly appreciated. Thank you!
Comment: Your indentation is inconsistent; this might result from pasting code with tab characters. You never use your `Boolean_IO`. `IF IsPrime = True THEN` is more clearly written as `IF ISPrime THEN`. The `'Img` attribute is specific to GNAT; that doesn't mean you shouldn't use it, but it limits your code's portability to other Ada compilers.
Comment: (1) How are you telling it what file to read from?  (2) What is the exact symptom: is the program exiting quietly, or are you seeing your "Data error" message or some other message, or is it hanging?  (3) Are you seeing any output about whether the first number is prime or composite?  (4) What numbers are in your input file?
Answer: Since you haven't described the exact symptoms (yet), I'm not sure whether this is the entire source of the problem or not.  However, the declaration
X : Natural := 2;

will initialize X at the beginning of the procedure only.  It does not reinitialize X every time it goes through the loop, because the declaration isn't inside the loop.  Therefore, after the program processes the first number N, X will be N-1 when you're done.  Since you don't reinitialize it, X will have that same value.  Then if the second number in your file is smaller than the first one, X will start at a number larger than this; since you keep incrementing it by 1 and only exit the loop when it becomes equal to [the new N] - 1, this will be a loooooooooooooooooooooooooong wait.
You can just say X := 2 at the beginning of your outer loop to reinitialize it.  Another possibility is to declare X as local inside the loop, instead of local to the whole procedure; something like
WHILE NOT End_Of_File LOOP
    Excep:
        DECLARE
            X : Natural := 2;
        BEGIN

and so on.
Keith's comments are worth following.  A couple other things: as a matter of practice, I would always write something like exit when X >= N - 1; instead of exit when X = N - 1;.  It shouldn't make a difference if you do things correctly, but this kind of thing can prevent hanging when something accidentally goes wrong.  Finally, look at your program and see what happens if 0 or 1 is in the input.  You print a message, but then you still go into the rest of your loop, which means that even if you reinitialize X correctly, you will still start X at 2 and then keep increasing it until it equals -1 or 0, which will never happen.  (Actually, it will, due to wraparound, but it will take a long time.)  Also, double-check your logic when N is 2.  You will either get the wrong answer or the program will hang.  OK, one other thing: in your inner loop, when you set IsPrime := false;, you still go through the rest of your loop, which is a waste of time.  Try instead
     IF S = 0 THEN
        IsPrime := False;
        exit;    -- No need to keep looping!
     END IF;

Comment: I am changing standard input through ada-guide environment. And yes  it was because I was not re-initializing my X value. Thank you all.

Ada loop stops after first input


How to fit a Pareto distribution via Bayesian estimation (with a Pareto prior)?

Question: I don't know Bayesian statistics very well, so I don't know if the question makes sense. Let me give an example.
We assume that the income distribution of a country is a Pareto distribution (the minimum is C, and the shape alpha is 3).
Now we want to estimate the income distribution of a specific company (it is inside this country). We assume that it is also a Pareto distribution and we have 100 observations.
With frequentist consideration, we can fit a Pareto distribution with these 100 observations (with MME or MLE). But I am wondering if it is possible to estimate with the prior distribution, which is the income distribution of a whole country.
And we consider that the minimum is the same, but we want to estimate the new shape alpha'.
Is it possible to consider that the prior distribution is the Pareto distribution (of the country, with known C and alpha) and after updating (with the 100 observations), we still get a posterior distribution that is a Pareto (with C, the same minimum and a new alpha)?
Comment: @Xi'an I got the impression from reading the quesiton that the OP doesn't understand what the prior is for and thinks that "Pareto prior" means that you have some vague prior assumption about the shape of the density which is then modified by data to some more complicated result (when of course you'd either have just a Pareto model under both approaches, or something more flexible under both).
Comment: My observation is that you've asked a series of questions about how to do Bayesian analysis, but don't have a strong understanding of the core idea very well. I don't say this to be mean-spirited, but I do think that you could benefit a great deal by picking up a textbook on the subject. This will give you the a level of knowledge that will help you ask more focused, well-informed questions. Gelman's Bayesian Data Analysis is very readable and a very good introduction to the topic. I strongly recommend it.
Comment: unclear: what is the parameter of interest? Minimum or shape or mean? and which parameter is modelled by your Pareto prior?
Comment: Also, `company` is nested within `country`?
Comment: @Glen_b Yes, I think that I don't understand bayesian theory very well. So my following consideration means nothing ? I consider that I know perfectly the income distribution of the country (which is a Pareto with known C and alpha). Now I want to calculate the distribution for a company and I assume that C is known (the same), and alpha is different. Is it possible to "update" alpha, with 100 observations from this company.
Answer: The phrasing is somewhat confusing, with countries and companies popping out of nowhere.
If the model is Pareto, i.e., $x_1,\ldots,x_n\sim\mathcal{P}(c,\alpha)$ and if $c$ has a Pareto prior $c\sim\mathcal{P}(d,\beta)$ then
$$c|x_1,\ldots,x_n\sim \pi(c|x_1,\ldots,x_n\sim)\propto \prod_{i=1}^n \mathbb{I}_{c\le x_i} c^{-n\alpha}\times \mathbb{I}_{d\le c} c^{-\beta-1}$$This leads to $$\pi(c|x_1,\ldots,x_n\sim)\propto \mathbb{I}_{d\le c\le \min_i x_i} c^{-n\alpha-\beta-1}$$a truncated Pareto.


Estimating confidence interval of a parameter from the MLE of another parameter

Question: Let's say I have a maximum likelihood estimate (MLE) for my parameter $\theta$ as in
$$\hat{\theta}\sim N\left(\theta, \frac{\theta^2}{n}\right) $$
and we have
$$\mu = \sqrt{\frac{\theta}{2}}$$
If I estimate my $CI(\theta)$ in the form of an interval $(min_{theta}, max_{theta})$, can I then use the following as a confidence interval for $\mu,$
$$ CI(\mu) = \left(\sqrt{\frac{min_{theta}}{2}}\: , \: \sqrt{\frac{max_{theta}}{2}}\right),$$
or am I doing something terribly wrong?
I've tested this using the CLT, so having $\mu\sim N(\mu, \frac{\sigma^2}{n}),$ and I'm a getting pretty good confidence interval, but I'd like to know if it's just a special case.
Comment: Could you please explain what your notation "$min_{theta},$" etc means?
Comment: @whuber thank you for asking, it's just the lower bound of the CI and the upper bound... i gave them some name just to reference them at the end
Comment: Thank you.  How do you plan to deal with situations where either or both of those bounds is *negative*?  This can happen even when $\theta$ itself is positive (although the chance of that happening depends on the value of $n,$ which you haven't described).  It's also curious that you attempt to describe your estimate $\hat\theta$ *in terms of itself* -- it appears on the right hand side of your first formula.  What do you really mean by that?
Comment: @whuber yes the function for $mu$ is just an example, and the $\hat{theta}$ it's for the Slutsky theorem (if i remember correctly), that "states" that we can use a "good approximation" and it's fine for example for convergence of CLT
Comment: @whuber this wants to be an example, saying "if we have a parameter $\theta$ estimated with MLE, and a second parameter $\gamma = h(\theta)$", and we use the confidence interval of $\theta$ to estimate the confidence interval of $\gamma$?
Comment: I know that I can use $\gamma = h(\theta)$ to calculate $\gamma$ in case $h()$ is injective, because of equivariance property of MLE, but i don't know if it holds for confidence interval
Comment: You lost me: no matter what theorem you might want to invoke, it makes no sense (in this context, anyway) to define a random variable recursively in terms of itself.  Your last comment is clear, though, and it has a simple answer: yes, *provided $h$ is a monotonic transformation.* This follows from the (intuitively clear) fact that an MLE of $h(\theta)$ is $h(\hat\theta).$
Comment: @whuber ok, no problem, removed the hat, I was just saying that we can use Slutsky theorem to say that the distribution converge even using the MLE of the parameter (and not the exact value).... but that's not the problem... my problem is to know if the _equivariance property of MLE_ holds also for Conf Intervals, and so given $\gamma = h(\theta)$, with $h$ injective, $CI(\gamma) = h(CI(\theta))$, and with $h(CI(\theta))$ i mean applying $h$ to the lower and upper bound of the confidence interval of $\theta$
Answer: The question, as clarified in comments, is a general one about confidence intervals.  It is best framed generally, because the generality strips away irrelevant details to bring out the main idea.
So, imagine a statistical estimation setting in which a sample $\mathbf X = (X_1,X_2,\ldots,X_n)$ is assumed to be governed by a probability law $F\in\Theta$ (a specified space of such laws).  A property is a real-valued function $\theta:\Theta\to\mathbb R.$ This is convenient language to talk about things we might want to know about $F$ and, by extension, any sample $\mathbf X$ governed by $F,$ while allowing for very general applications.
By definition, a confidence interval procedure (of size $\alpha$) for a property $\theta$ is a pair of functions $l, u,$ defined on the set of all possible samples, for which
$$\inf_{F\in\Theta}{\Pr}_F\left[l(\mathbf X) \le \theta(F) \le u(\mathbf X)\right] = 1-\alpha.\tag{*}$$
(It is my purpose not to mention issues related to measurability or how things might depend on the sample size $n,$ because these would just be distractions from the main idea.)
This looks painfully abstract but conveys a relatively straightforward idea. The left hand side concerns the chance that the interval $[l(\mathbf X), u(\mathbf X)],$ as computed from the sample, covers the true (but unknown) value $\theta(F).$  The infimum applied to it means that the coverage probability might depend on $F,$ but is never less than $1-\alpha$ and can approach it arbitrarily closely (or even equal it).
The question concerns a transformation $h$ of the property.  That is, $h:\mathbb R \to \mathbb R$ is some function or partial function, such as the square root (which is defined only for non-negative numbers).  When the property $\theta$ takes on values in the domain of $h,$ then the composition of $\theta$ followed by $h,$ $h\circ \theta:F\to h(\theta(F)),$ is also a property.  The question asks:

Given a property $\theta,$ a confidence interval procedure $(l,u),$ and a transformation $h,$ is it the case that $(h\circ l, h\circ u)$ is a confidence interval procedure for $h\circ\theta$?

In some special but common cases--usually not including the square root function in the question--the answer is yes.  Specifically, assume

$h$ is a strictly  increasing function and

The values of all upper and lower limits are in the domain of $h.$

Condition (2) assures the question even makes sense, while condition (1) guarantees that the event $l(\mathbf X) \le \theta(F) \le u(\mathbf X)$ is equivalent to the event $h\circ l(\mathbf X) \le h\circ\theta(F) \le h\circ u(\mathbf X).$  Since for any given $F$ these are the same events (as implied by the strict monotonicity of $h$), they have the same probability.  Thus, the infimum in the defining equation $(*)$ is still $1-\alpha.$
That's all there is to it.  But let's restate the result in English:

Because when a transformation $h$ is strictly increasing, any interval $[\lambda, \upsilon]$ covers $\theta$ if and only if $[h(\lambda), h(\upsilon)]$ covers $h(\theta),$  a  procedure $l,u$ is a $1-\alpha$ confidence interval for a property $\theta:\Theta\to\mathbb R$ if and only if $h\circ l, h\circ u$ is a $1-\alpha$ confidence interval procedure for the property $h\circ\theta.$

Wait a second, you might be asking: aren't there cases where this result obviously is false?  Consider a confidence interval for the mean of a Lognormal distribution. (We say $X$ has a Lognormal distribution when $\log(X)=Y$ has a Normal distribution.)  This is a challenging problem with various complicated solutions.  But if we let $h$ be the logarithm, then upon applying $h$ to $X$ we seem to have reduced the question to finding a confidence interval for the mean of a Normal distribution, which is simple and well known.
The resolution of this conundrum is that it's an apparent paradox of terminology, not of estimation.  The preceding analysis has shown only that exponentiating the endpoints of a confidence interval for a Normal mean will give a confidence interval for the exponential of the Normal mean.  However, the exponential of that mean is not the mean of the corresponding lognormal distribution.  Indeed, when $Y$ has a Normal$(\mu,\sigma^2)$ distribution, the mean of $X=\exp(Y)$ is not $\exp(\mu):$ instead, it is $\exp(\mu + \sigma^2/2).$
To put it the other way: $\exp(\mu)$ is the geometric mean of the Lognormal distribution.  We conclude that the exponentials of the limits of a CI for the mean of a Normal distribution give a CI for the geometric mean of the corresponding Lognormal distribution.
Thus, the paradox is resolved by pointing out that

$h(\theta)$ and $\theta,$ as properties of $h(\mathbf X)$ and $\mathbf X,$ respectively, might not necessarily be called by the same names.

Finally, just to conclude this example: A confidence interval for the arithmetic mean of a sample $\mathbf X$ from a Lognormal$(\mu,\sigma^2)$ distribution is equivalent to a confidence interval for the property $\mu+\sigma^2/2$ in a sample $\mathbf Y$ from a Normal$(\mu,\sigma^2)$ distribution.  One merely has to exponentiate the latter.  Proof: the exponential is defined everywhere and is strictly increasing.
Comment: thank you so much, this is amazing
Comment: just to conclude the answer, for the 2 points you listed, then in the example show, we actually can do the transformation of the CI from one parameter to the other, since the sqrt is defined for each sup and inf of $theta/2$, and because h is a strictly increasing function (but we would have to define $\theta > 0$ to avoid having the sqrt of negatives)
Comment: Don't confuse the values of the limits with the parameter! Although the *parameter* $\theta$ might be positive, there is some chance that one or even both limits will be *negative* in your situation.  Thus you cannot leap to the conclusion that your approach works.  What is needed is an argument that it is very improbable for the lower limit to be negative.  That will be the case as $n$ grows large.
Comment: can you please point to some reference to the lim sup and lim inf you are referring to? i might be confusing the definition or what thing you are referring to in the phrase _The values of all upper and lower limits_
Comment: I am not referring to lim inf or lim sup: I am discussing the usual confidence limits.  You have posited a situation in which data are drawn from some kind of Normal distribution.  It is perfectly possible for a lower confidence limit to be negative even when the mean of the underlying distribution itself is positive.
Comment: ok it makes totally sense


An olympiad question

Question: I came across a question ( mentioned below ) which is from a Mathematical Olympiad.
It says,
If $m $ and $n $ are positive integers such that

$n + (n + 1) + (n + 2) +...+ (n + m) = 1000 $

then how many $(m, n)$ pairs exists ?
Comment: And you've been a member of this site for almost 20 months and you've asked some 13 questions. You should really try to translate the question into english and write it down.
Comment: Do you not understand what the questions is asking or do you not know how to solve it? If it is the first, please make that more clear. If it's the second, what attempts have you made?
Comment: @DonAntonio The OP could have asked at the end "Answer desired in English and in Turkish" :-)
Comment: As a way to get started:  Note that the expression on the left is the difference of two triangular numbers.  Triangular numbers have a simple expression.
Comment: What have you tried, and where did you have your difficulties?
Comment: Also a duplicate of [this](https://math.stackexchange.com/q/139842/11619).
Answer: $n(m+1)+(1+2+\cdots+m)=1000$
$n(m+1)+\dfrac 12m(m+1)=1000$
$(m+1)(2n+m)=2000$
Note that $m+1$ and $m+2n$ are of opposite parities. We have to factorize $2000$ into the product of an odd and an even number.
Note that both factors should be greater than $1$ as $m$ is positive.
$2000=5\times400=25\times80=125\times16$
Note also that $m+1<2n+m$.
So, $(m+1,2n+m)=(5,400)$ or $(25,80)$ or $(16,125)$
$(m,n)=(4,198)$ or $(24, 28)$ or $(15,55)$.
Comment: For completeness, you forgot $1\times 2000$ or forgot to state that of course the factors must be $>1$

An olympiad question


What do you call a chord that is not complete?

Question: What do you call a chord that is not complete or how can you tell what chord a group of notes are?
Is it by looking at the root note?
For example:

    C# E G# B F#    =>    C# Maj 11
    E F# G#         =>    ???        // What chord is this?
                                     // I'm guessing E because its the root?

    B F G           =>    C G7 Chord  // Why is this not a B Chord?
    B F# E#         =>    C Diminished G7 Chord ?

    B C# F#         =>    Is this even a chord? If not, how so?

Furthermore to the question. Is there a chord for every single triad or 3 note?
What I mean is, is there a chord for every indirectly related three notes?
How do you even know when its not a chord?
Note: The instrument I'm talking about is a piano.
Comment: When I read the question title, it sounds like a riddle that needs a punchline. What do you call a chord that is not complete? A chor.
Comment: Your first chord is certainly not C#maj11. The E makes it minor for starters.
Comment: In theory, every group of three or more notes is a chord, but not every chord has a commonly accepted name. There isn't some algorithm for computing the name of a chord given the notes in it; you just have to know the names.
Comment: Generally speaking, any chord will have notes at least a tone apart. Play C, C# and D together, and it's hardly a chord with any mileage in it. One would be hard pushed to find a good place to play it - except somewhere where no-one else could hear it- and it could be quite difficult to give it a sensible name.
Answer: I'll address the B F G question first... the simplest way to put these notes into a "common practice" chord is to arrange them with G as the root, i.e. G B (D) F == G7.  Try spelling the chord with B or F as the root for comparison!  Yuck.
Also, it is quite common, when voicing a dominant 7 chord with only three voices, to eliminate the fifth (D in this case).  This is because it isn't critical to the "quality" of the chord and having it doesn't really add anything.  A perfect fifth above the root is pretty much implicit.  So the fact that there is no D in what we are calling a G7 is not a surprise, in fact I'd say it strengthens the case for it being a G7.
With B in the bass, this is a first-inversion chord.
Finally, what does your ear tell you?  Play these chords back-to-back on the piano:
C (Maj) :  C E G
then
G7 / B  :  B F G
Does this sound familiar?  It should.  It's a simple I-V in C.
For many of the other examples, the answer to "what is this chord" depends a lot on context.  What comes before, and probably more importantly, what comes next?
B C# F#
Without context (and to some degree, what's in the bass), it's impossible to say if this is a B Major-type of chord, with an added 9 (C#) for color; or a C# Dominant-type of chord, with the F# hanging over from the previous chord, waiting ("sustaining") to move to E# and form C#7, the dominant chord in F#/f#-; or an F# chord, with the B sustained from the previous chord, waiting to move to A# to form F# Major (or to A to make f#-); or, perhaps, something else entirely!
Answer: Not every group of notes has a name, but with most you can put together some name. Your first unknown E, F#, and G# can be looked at an Eadd9 (thanks Charles).  Your last example B,  C#, and  F# is just a Bsus2.
A chord is technically any set of 3 or more notes so technically any group of 3 or more notes is a chord regardless if it seems to be missing notes or not. Most chords are nameable and all set of notes can be reduced to a prime form which is a very computational way of looking at chords.
To name chords based on notes can sometimes be tricky especially since some groups of notes yield multiple chord names, but there are ways to look at groups of notes to see what chords they make. Here are a few things to remember when looking at groups of notes to name chords:

The bass note is not always the root of the chord.
Chords are typically built in 3rds, so try and stack the given notes in thirds.
The 5th of a chord can typically be omitted.

A little trick I use when naming chords is to take the note I think is the root of the chord and compare it against the major scale with a lowered 7th (the Mixolydian mode). The reason I do this is because how common the dominant 7th chord is and how extentions typically line up very well with this scale. I'll show you with the examples givin.
EX1 - C# E G# B F#
We can see that the first 4 notes stack up nicely in 3rds so let's assume C# is the root. Now we compaire all the notes to the C# Mixolydian scale:

C#  D#  E#  F#  G#  A#  B
C#  X   E   F#  G#  X   B

As you can see we have a 3rd, 5th and 7th. The 3rd is lowered which is fine it just means the basic triad is minor. We don't have a 9th or a 13th, but we do an 11th. From this information we can call the chord a C#m11.
EX2 - E   F#  G#
We only have three notes in this chord and they are all next to each other step wise. We can guess that is E is the root and let's compare the notes to the E Mixolydian scale:

E   F#  G#  A   B   C#  D
E   F#  G#  X   X   X   X

As you can see we have a 3rd, but we are missing a 5th and 7th. Missing the 5th is not a big deal, but because there is no 7th any extensions need be considered "added". There is one extension a 9th so from this the chord is an Eadd9.
Will finish the others soon...
Answer: The first one can be E6/9. The instrument it's played on is inconsequential. More to follow.
EDIT: 5 yrs on! E F♯ G♯ - an E chord with no 5th, common enough. There is a M3, so major of some sort. The F♯ is extra, not suspending the M3, so it's Eadd9.
B F G won't be a B chord - the only diatonic note there would be B! Try G7. It has root - G, M3 - B and ♭7 - F.
B F♯ E♯. If root is B, then E♯ isn't diatonic. Next to F♯ might have made a maj7, but that would need root of F♯. No real useful chord, probably a passing note 'chord'.
B C♯ F♯. Simple Bsus2. B is root, F♯ is P5, leaving C♯ as the M2, but since there's no 3 of any kind, the M2 is called suspended. Often it moves in the next harmony to the 3. Thus Bsus2.
As in my recent comment, the first chord isn't C♯ major anything. With an E, it must be minor if the C♯ is root. E6/9 seems a reasonable name - more exactly E6/9/C♯.
Answer: By definition all chords are "complete" if they have 3 or more notes performed at the same time. But depending on how it is used (ie is there a pedal, chords/melody coming from and progressing to etc...) will help you understand its function and therefore can help you in naming it.
Function can be thought of as chords that sound at rest or chords that sound tense in the listeners ear.
Another way to think of function is tonic chords (either M or m) and dominant chords (V7 chords). Tonic chords are typically chords that are used for resolution and dominant chords are the chord types that need resolution.
All this was standardized way back by the great master JS Bach himself and we still seem to appreciate music based on this formula. (Just to make things a little more complicated there is another type of chord function and that is the pre-dominant a chord that leads to the dominant).
So you see you can not just ask what is the formula for figuring out a chord (set of 3 or more pitches) it has to thought of in its entirety.
So the better question would be how does this group of notes function?
Hope this helped.


Convergence of $a_n \geq a_{n+1} -s_n$

Question: Let $(a_n)_{n  \in \mathbb{N}}$ and $(s_n)_{n  \in \mathbb{N}}$ be sequences in $[0, \infty)$ so that $\sum\limits_{n=0}^{\infty}s_k$ converges and
$a_n \geq  a_{n+1} -s_n ~~~~~~(n \in \mathbb{N})$
Show that $(a_n)_{n  \in \mathbb{N}}$ is convergent.
A hint is given, i should sight the sequence $(b_n)_{n  \in \mathbb{N}}$ with $b_n = a_n-\sum\limits_{n=0}^{n-1}s_k$ for $n \in \mathbb{N}$ first.
My idea is to show that the sequence is bounded above and monotonically nonincreasing. But how to do this?
Comment: Consider that $b_n$ is nonincreasing
Answer: We have
$$b_{n+1}-b_n=a_{n+1}-a_n-s_n\le0$$
so the sequence $(b_n)$ is decreasing and $$b_n=a_n-\sum_{n=0}^{n-1}s_k\ge a_n-\sum_{n=0}^\infty s_k\ge-\sum_{n=0}^\infty s_k=C$$
hence $(b_n)$ is bounded below by $C$ so it's convergent. The convergence of $(a_n)$ can be deduced easily.
Comment: You have the nice skill of saying "enough" without saying "too much"! +1

Convergence of $a_n \geq a_{n+1} -s_n$


Execute some steps before REST POST request

Question: I have created a custom content type and configured it to be created via REST POST method using REST client like POSTMAN or any frontend(like angularJS or react).
I want to execute few steps before creation of content type when a POST request is made. For example, make a SOAP call to SAP or make a query to external DB, and based on some condition like if data is received from SAP or external DB, then only content type should be created else it should throw some custom error.
I am new to Drupal and any guidance is welcome.
Answer: There is a hook called entity_presave.
This is always called when you persist a new or updated entity through Drupal API.
You can always check for the current request's method to see if it was a POST method (you can also check for the route itself).
So these presave changes (or can be save or post save) will be only taken place if that criteria is met.


método JSON.stringify()

Question: Tenho uma dúvida sobre o método JSON.stringify().
Realizando a consulta desses valores em uma tebela de membro:
{
    "NProjetos": [
        {
            "idProjeto": 2,
            "nomeProjetos": "SGI"
        }
    ],
    "cargo": "Desenvolvedor",
    "descricao": "Desenvolvedor PHP, JAVA",
    "id": 2,
    "imgMembros": [
        {
            "idImg": 2,
            "url": "img/diego.png"
        }
    ],
    "nome": "Diego Rabelo",
    "stats": 3
};

Com
JSON.stringify(membro.NProjetos, ['nomeProjetos']); //retorno:  [{"nomeProjetos":"SGI"}]

JSON.stringify(membro.nomeProjetos); //não tem retorno.

Como eu poderia pegar só o valor, no caso "SGI"?
Comment: E essa aspa dupla faltando em `"NProjetos"`? Foi erro na hora de escrever a pergunta ou tá errado no código?
Comment: Não é um JSON válido, primeiro você pode testar por aqui: http://jsonlint.com/
Comment: Aliás, o que é **`membro`** em `JSON.stringify(membro.nomeProjetos)`? Aparentemente sua dúvida é simples, mas não dá pra entender o que você quer.
Comment: Erro de digitação mesmo, Jbueno.
Comment: Acredito que se seu interesse for pegar somente o valor, você pode simplesmente usar: `var nomeProj = membro.NProjetos[0].nomeProjetos`, do que fazer stringify.
Comment: Pelo que entendi é isso também @LucasCosta, mas minha dúvida é,Ítalo, podem vir `N` projetos certo? você quer o `nomeProjetos` de todos?
Comment: Baseado no JSON https://jsfiddle.net/lbclucascosta/5n8wdtmg/
Comment: Obrigado, Lucas. É isso mesmo Kenny.
Answer: Se queres obter um JSON ou um array com todos os valores de "nomeProjetos " dentro de "NProjetos" basta mapeares essa array assim:
var nProjetos = membro.NProjetos.map(el => el.nomeProjetos);

ou em JavaScript menos moderno:
var nProjetos = membro.NProjetos.map(function(el){
    return el.nomeProjetos
});

e depois para criar um JSON:
var json = JSON.stringify(nProjetos);

Exemplo: https://jsfiddle.net/jw3mgwms/
Answer: Sendo membro o seu Json descrito na pergunta, você deve pegar primeiramente os valores. O problema não é especificamente no método JSON.stringify()
var projetos = []

for(var i = 0 ; i < membro.NProjetos.length ; i++){
    projetos.push(membro.NProjetos[i].nomeProjetos)
}

Ou, se estiver usando JQuery
var projetos = []

$.each(membro.NProjetos, function(){
    projetos.push($(this).nomeProjetos);
});

Se preferir pode usar map também do JQuery
var projetos = []

$.map(membro.NProjetos, function(projeto, i){
   projetos.push(projeto.nomeProjetos);
});

Com isso, você terá um array projetos, onde terá o nome de todos os projetos do seu Json.
Answer: Você pode mapear os nomes dos projetos em um novo array usango o Array#map:
var projetosMembros = membros.NProjetos.map(proj => {
  return proj.nomeProjetos;
});

var membros = {"NProjetos": [{"idProjeto": 2,"nomeProjetos": "SGI"}],"cargo": "Desenvolvedor","descricao": "Desenvolvedor PHP, JAVA","id": 2,"imgMembros": [{"idImg": 2,"url": "img/diego.png"}],"nome": "Diego Rabelo","stats": 3};

var projetosMembros = membros.NProjetos.map(proj => {
  return proj.nomeProjetos;
});

console.log(projetosMembros);

Com laço clássico de repetição (ECMA5):
for (var i = 0 ; i < membros.NProjetos.length ; i++){
    projetosMembros.push(membros.NProjetos[i].nomeProjetos);
}

var membros = {"NProjetos": [{"idProjeto": 2,"nomeProjetos": "SGI"}],"cargo": "Desenvolvedor","descricao": "Desenvolvedor PHP, JAVA","id": 2,"imgMembros": [{"idImg": 2,"url": "img/diego.png"}],"nome": "Diego Rabelo","stats": 3};

var projetosMembros = [];
for (var i = 0 ; i < membros.NProjetos.length ; i++){
    projetosMembros.push(membros.NProjetos[i].nomeProjetos);
}

console.log(projetosMembros);
Answer: dado o objeto
membro = {
    "NProjetos": [
        {
            "idProjeto": 2,
            "nomeProjetos": "SGI"
        }
    ],
    "cargo": "Desenvolvedor",
    "descricao": "Desenvolvedor PHP, JAVA",
    "id": 2,
    "imgMembros": [
        {
            "idImg": 2,
            "url": "img/diego.png"
        }
    ],
    "nome": "Diego Rabelo",
    "stats": 3
};

JSON.stringify() serve para transformar o JSON em uma stringy mas pelo que entendi de sua duvida vc não quer fazer isso, vc apenas usou pois não sabia outro modo de pegar o conteúdo
Explicação do porque o codigo não funcionou como você queria
JSON.stringify(membro.nomeProjetos); //não tem retorno.
ao digitar membro.nomeProjetos você esta acessando a variavel membro ( que é o objeto json) e logo em seguida tentou usar o objeto nomeProjetos porem esse objeto não existe neste nivel vc deve entrar primeiro em Nprojetos  depois acessar o array e depois acessar o elemento  nomeProjetos
creio eu que vc queria fazer o seguinte .....
newJson = JSON.parse(JSON.stringify(membro.NProjetos[0])) //Cria um novo json como se fosse (em toscamente) um subConjunto de membro
newJson.nomeProjetos // acessa

ou acessar direto
membro['NProjetos'][0]['nomeProjetos']
//ou
membro.NProjetos[0].nomeProjetos

Answer: Entendi sua pergunta e tenho a solução correta.
No entanto, não sei se quer fazer isso por falta de opção ou conhecimento.
Por isso, trago duas soluções:

Aquela que responde sua pergunta;
Aquela que simplifica sua vida.

respondendo sua pergunta
Segundo a MDN web docs:

O método JSON.stringify() converte um objeto ou valor JavaScript, em uma string JSON. Opcionalmente substitui valores, se uma função de substituição é passada ou, opcionalmente, converte somente propriedades especificadas em uma array de substituição.

A array de substituição nada mais é que uma lista, onde você coloca o nome de cada propriedade que deseja incluir na conversão.

let selecionado
let humano;

humano = {
  nome: "José",
  idade: 33,
  altura: "1.8m"
}

// output: {"nome":"José","idade":33}
selecionado = JSON.stringify(humano, ["nome", "idade"]);
console.log(selecionado);

// output: {"nome":"José"}
selecionado = JSON.stringify(humano, ["nome"]);
console.log(selecionado);

Já a função de substituição, é um callback que recebe dois argumentos: um com o nome do objeto e outro com o valor.
Essa função pode usar os argumentos para modificar ou filtrar o valor.
Quando a função retorna undefined, o valor é filtrado (removido da conversão).
Quando a função retorna algo diferente de undefined, este valor é utilizado na conversão.

let substituido
let humano;

humano = {
  nome: "José",
  idade: 44,
  altura: "1.8m"
}

function substituicao(name, value) {

  if (value.idade != 44) return undefined

  return `${value.idade}`
}

// output: "José"
substituido = JSON.stringify(humano, (name, value) => value.nome);
console.log(substituido);

// output: 66
substituido = JSON.stringify(humano, substituicao);
console.log(substituido);

Desse modo, a solução para sua pergunta seria essa:

let projetos,
membro;

function substituicao(name, projetos) {

  let nomes;

  nomes = projetos.map(projeto => projeto.nomeProjetos);
  nomes = nomes.join(", ");

  return nomes;
}

membro = {
  "NProjetos": [
  {
      "idProjeto": 2,
      "nomeProjetos": "SGI"
  }
  ],
  "cargo": "Desenvolvedor",
  "descricao": "Desenvolvedor PHP, JAVA",
  "id": 2,
  "imgMembros": [
  {
      "idImg": 2,
      "url": "img/diego.png"
  }
  ],
  "nome": "Diego Rabelo",
  "stats": 3
};

projetos = JSON.stringify(membro.NProjetos, substituicao);
console.log(projetos);

simplificando a vida
Se você não precisa converter o objeto em string, antes de filtrar os nomes de projetos, poderias mapeá-los deste modo:

let nomes;

membro = {
  "NProjetos": [
  {
      "idProjeto": 2,
      "nomeProjetos": "SGI"
  }
  ],
  "cargo": "Desenvolvedor",
  "descricao": "Desenvolvedor PHP, JAVA",
  "id": 2,
  "imgMembros": [
  {
      "idImg": 2,
      "url": "img/diego.png"
  }
  ],
  "nome": "Diego Rabelo",
  "stats": 3
};

projetos = membro.NProjetos.map(projeto => projeto.nomeProjetos);
nomes = projetos.join(", ");

console.log(nomes);

método JSON.stringify()


Do I need to take out any predictors from multiple regression if I put in some principal components as additional predictors?

Question: I have an assignment which involves one area-level dataset made of $366$ scale variables. I have to perform PCA, compare it with rates of an additional response variable $X$, and comment on its face validity.
I also have to do a regression analysis to predict rates of variable $X$.
I would like to be clever and add the PCA scores to the regression to see if it improves the predictive power of the model.
Question: I do not want to overestimate the predictive power of certain variables within the dataset. Do I have to exclude variables from the regression that are structurally related to the PCs that I put in? The PCA is very theory based and is done already, so I don't really want to mess with it.
Comment: "I would like to be clever" -- famous last words in statistics.
Answer: It does not make any sense to add (any number of) principal components (PCs) to your $366$ predictors. This cannot possibly improve the quality of the model, because PCs are linear combinations of the original predictors and so by adding them you add nothing new. Instead, you make the regression degenerate, and quite likely will get an error from your software.
You could in principle add some PCs and remove some original variables, e.g. the ones that are most highly correlated with the PCs you are adding; this is an option that you are asking about. I would argue that this is very unlikely to make sense, because again, by adding PCs you do not add any new information, so should not expect the model to improve.
Somewhat paradoxically, it can make a lot of sense to remove the original predictors altogether and replace them by several (e.g. $5$ or $10$, but much less than $366$) PCs. This procedure even has a name! it is called "principal components regression" (PCR). Even though here, again, you do not add any new information, you remove a lot of predictors and will often end up removing a lot of useless predictors. Useless predictors tend to spoil your model (this is known as "overfitting"), and removing them can improve the model (this is known as "regularization"). You might want to read this recent answer of mine for some further remarks on PCR and for some links to further discussions.
This is a subtle point, so take a moment to appreciate it: adding redundant information cannot improve the model, but removing useless information can.
Comment: I know I am a couple of years late responding to your answer, but it was indeed very useful. I am still using the last point in my studies. Thank you for replying
Comment: Thanks for the tips, I hope to continue to use this great platform when I am less sleep deprived (new mother) and in work, so its good to know how to be as polite as I am in person :)
Comment: Congratulations, @MissD! :)
Comment: Hi @MissD, that's indeed nice to hear :-) Please consider "accepting" my answer by clicking on a green tick sign to the left of it. Once you have 15 reputation points, you will be able "upvote" my answer too by clicking on an upper arrow to the left of it. That's a way to say thank you here. Cheers!
Answer: There are cases when some of the original variables that were used in a PCA are no longer available (e.g. a follow-up of an old experiment or published sources not disclosing raw data). Leaving aside the question whether you should trust such (essentially unreproducible) data, let's imagine you need to use a certain PC as a predictor of a newly collected response variable, alongside a couple of raw predictor variables, which may have been used in the original PCA.
In this case, you could check for correlations between individual variables and principal components you intend to use. If you had many, many raw variables, chances are that correlation of any one of them with a single PC is not very strong. But if you already had strong cross-correlations for variables going into PCA, you are likely to be overestimating them thrice.
As indicated by amoeba above and below, since PCs are linear combinations of the original variables, using all the PCs alongside all raw variables that went into a PC is a meaningless exercise. And if you still have all the original variables used in PCA, it makes much more sense to do what amoeba suggested in the comment above.
Comment: I can't get my head around even the starting point here. You're talking about situations where you don't have the original data, but you do have (the numerical values of) the PCs? In that situation, if it arises, how could you possibly know what you were using? How often does this arise? For that and other reasons already stated, this seems very strange advice and quite unsound in so far as I can follow it.
Comment: (-1) PCs are linear combinations of original variables. Adding them to the model should change *nothing* in the predictive power, because one is not adding independent predictors. Adding PCs without removing any original features is pointless and futile.
Comment: I'm surprised the regression runs at all without rank-deficient error.
Comment: @amoeba - You are correct if you add all PCs and all predictors. It is not the case if you add only one of the PCs and some of the original variables, though. I tried it with some of my data, using PC1 and 2 of 23 raw variables, both with unremarkable loadings on that PC. Predictive power of the model increased from 0.15 to 0.18. qed.
Comment: Yes, sure, but that is not what your last sentence says: *"adding [PCs as] extra variables will always improve ... the model"*. I will be happy to reverse my downvote if you make this clear. If you go as far as to mention principal components regression and explain what that is, I will even happily upvote :)
Comment: Thank you for your advice - I have taken it on board. Any word on the substantive model building question will be much appreciated and well received. Just for clarification I have reworded the question here: Now I have a PCA to add to my final model, should I discount variables that have a structural relationship to those included in the PCA, so as not to overestimate?
Comment: @MissD: my edited post hopefully answers the second part, but just to be clear - we are not talking about 'a PCA' to add (presumably meaning all PCs?), just one PC component of it; *all* raw variables will have a relationship with it, but some may not be very strong. I am not sure what's 'substantive model building' - a quick search gives an economics definition involving 'precise definition of incorporated concepts', if that's the case (?), yeah, by all means state what you are analyzing.
Comment: @amoeba - right, I clarified that in the edited version; extra vars just referred to MR, I removed that since it is confusing. I won't add pcr because (a) your linked answer does that quite well and (b) I was operating under the assumption PCs are "done already"/raw data unavailable, which I've now specified.
Comment: @katya, thanks, I removed my downvote. I am a bit confused though as to why you operate under the assumption that the raw data are (or might be) unavailable; the OP clearly states that the raw data are there and PCA is done as part of the exercise...


e2fsck extremely slow, although enough memory exists

Question: I've got this external USB-Disk:
kaefert@blechmobil:~$ lsusb -s 2:3
Bus 002 Device 003: ID 0bc2:3320 Seagate RSS LLC

As can be seen in this dmesg output, there is some problem that prevents that disk from beeing mounted:
kaefert@blechmobil:~$ dmesg
...
[  113.084079] usb 2-1: new high-speed USB device number 3 using ehci_hcd
[  113.217783] usb 2-1: New USB device found, idVendor=0bc2, idProduct=3320
[  113.217787] usb 2-1: New USB device strings: Mfr=2, Product=3, SerialNumber=1
[  113.217790] usb 2-1: Product: Expansion Desk
[  113.217792] usb 2-1: Manufacturer: Seagate
[  113.217794] usb 2-1: SerialNumber: NA4J4N6K
[  113.435404] usbcore: registered new interface driver uas
[  113.455315] Initializing USB Mass Storage driver...
[  113.468051] scsi5 : usb-storage 2-1:1.0
[  113.468180] usbcore: registered new interface driver usb-storage
[  113.468182] USB Mass Storage support registered.
[  114.473105] scsi 5:0:0:0: Direct-Access     Seagate  Expansion Desk   070B PQ: 0 ANSI: 6
[  114.474342] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[  114.475089] sd 5:0:0:0: [sdb] Write Protect is off
[  114.475092] sd 5:0:0:0: [sdb] Mode Sense: 43 00 00 00
[  114.475959] sd 5:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[  114.477093] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[  114.501649]  sdb: sdb1
[  114.502717] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[  114.504354] sd 5:0:0:0: [sdb] Attached SCSI disk
[  116.804408] EXT4-fs (sdb1): ext4_check_descriptors: Checksum for group 3976 failed (47397!=61519)
[  116.804413] EXT4-fs (sdb1): group descriptors corrupted!
...

So I went and fired up my favorite partition manager - gparted, and told it to verify and repair the partition sdb1.
This made gparted call e2fsck (version 1.42.4 (12-Jun-2012))
e2fsck -f -y -v /dev/sdb1

Although gparted called e2fsck with the "-v" option, sadly it doesn't show me the output of my e2fsck process (bugreport https://bugzilla.gnome.org/show_bug.cgi?id=467925 )
I started this whole thing on Sunday (2012-11-04_2200) evening, so about 48 hours ago, this is what htop says about it now (2012-11-06-1900):
  PID USER      PRI  NI  VIRT   RES   SHR S CPU% MEM%   TIME+  Command
 3704 root       39  19 1560M 1166M   768 R 98.0 19.5 42h56:43 e2fsck -f -y -v /dev/sdb1

Now I found a few posts on the internet that discuss e2fsck running slow, for example:
http://gparted-forum.surf4.info/viewtopic.php?id=13613
where they write that its a good idea to see if the disk is just that slow because maybe its damaged, and I think these outputs tell me that this is not the case in my case:
kaefert@blechmobil:~$ sudo hdparm -tT /dev/sdb
/dev/sdb:
 Timing cached reads:   3562 MB in  2.00 seconds = 1783.29 MB/sec
 Timing buffered disk reads:  82 MB in  3.01 seconds =  27.26 MB/sec

kaefert@blechmobil:~$ sudo hdparm /dev/sdb
/dev/sdb:
 multcount     =  0 (off)
 readonly      =  0 (off)
 readahead     = 256 (on)
 geometry      = 364801/255/63, sectors = 5860533160, start = 0

However, although I can read quickly from that disk, this disk speed doesn't seem to be used by e2fsck, considering tools like gkrellm or iotop or this:
kaefert@blechmobil:~$ iostat -x
Linux 3.2.0-2-amd64 (blechmobil)    2012-11-06  _x86_64_    (2 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
          14,24   47,81   14,63    0,95    0,00   22,37

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda               0,59     8,29    2,42    5,14    43,17   160,17    53,75     0,30   39,80    8,72   54,42   3,95   2,99
sdb             137,54     5,48    9,23    0,20   587,07    22,73   129,35     0,07    7,70    7,51   16,18   2,17   2,04

Now I researched a little bit on how to find out what e2fsck is doing with all that processor time, and I found the tool strace, which gives me this:
kaefert@blechmobil:~$ sudo strace -p3704
lseek(4, 41026998272, SEEK_SET)         = 41026998272
write(4, "\212\354K[_\361\3nl\212\245\352\255jR\303\354\312Yv\334p\253r\217\265\3567\325\257\3766"..., 4096) = 4096
lseek(4, 48404766720, SEEK_SET)         = 48404766720
read(4, "\7t\260\366\346\337\304\210\33\267j\35\377'\31f\372\252\ffU\317.y\211\360\36\240c\30`\34"..., 4096) = 4096
lseek(4, 41027002368, SEEK_SET)         = 41027002368
write(4, "\232]7Ws\321\352\t\1@[+5\263\334\276{\343zZx\352\21\316`1\271[\202\350R`"..., 4096) = 4096
lseek(4, 48404770816, SEEK_SET)         = 48404770816
read(4, "\17\362r\230\327\25\346//\210H\v\311\3237\323K\304\306\361a\223\311\324\272?\213\tq \370\24"..., 4096) = 4096
lseek(4, 41027006464, SEEK_SET)         = 41027006464
write(4, "\367yy>x\216?=\324Z\305\351\376&\25\244\210\271\22\306}\276\237\370(\214\205G\262\360\257#"..., 4096) = 4096
lseek(4, 48404774912, SEEK_SET)         = 48404774912
read(4, "\365\25\0\21|T\0\21}3t_\272\373\222k\r\177\303\1\201\261\221$\261B\232\3142\21U\316"..., 4096) = 4096
^CProcess 3704 detached

around 16 of these lines every second, so 4 read and 4 write operations every second, which I don't consider to be a lot..
And finally, my question: Will this process ever finish? If those numbers from fseek (48404774912) represent bytes, that would be something like 45 gigabytes, with this beeing a 3 terrabyte disk, which would give me 134 days to go, if the speed stays constant, and e2fsck scans the disk like this completly and only once.
Do you have some advice for me? I have most of the data on that disk elsewhere, but I've put a lot of hours into sorting and merging it to this disk, so I would prefer to getting this disk up and running again, without formatting it anew. I don't think that the hardware is damaged since the disk is only a few months and since I can't see any I/O errors in the dmesg output.
UPDATE: I just looked at the strace output again (2012-11-06_2300), now it looks like this:
lseek(4, 1419860611072, SEEK_SET)       = 1419860611072
read(4, "3#\f\2447\335\0\22A\355\374\276j\204'\207|\217V|\23\245[\7VP\251\242\276\207\317:"..., 4096) = 4096
lseek(4, 43018145792, SEEK_SET)         = 43018145792
write(4, "]\206\231\342Y\204-2I\362\242\344\6R\205\361\324\177\265\317C\334V\324\260\334\275t=\10F."..., 4096) = 4096
lseek(4, 1419860615168, SEEK_SET)       = 1419860615168
read(4, "\262\305\314Y\367\37x\326\245\226\226\320N\333$s\34\204\311\222\7\315\236\336\300TK\337\264\236\211n"..., 4096) = 4096
lseek(4, 43018149888, SEEK_SET)         = 43018149888
write(4, "\271\224m\311\224\25!I\376\16;\377\0\223H\25Yd\201Y\342\r\203\271\24eG<\202{\373V"..., 4096) = 4096
lseek(4, 1419860619264, SEEK_SET)       = 1419860619264
read(4, ";d\360\177\n\346\253\210\222|\250\352T\335M\33\260\320\261\7g\222P\344H?t\240\20\2548\310"..., 4096) = 4096
lseek(4, 43018153984, SEEK_SET)         = 43018153984
write(4, "\360\252j\317\310\251G\227\335{\214`\341\267\31Y\202\360\v\374\307oq\3063\217Z\223\313\36D\211"..., 4096) = 4096

So the numbers in the lseek lines before the reads, like 1419860619264 are already a lot bigger, standing for 1.29 terabytes if those numbers are bytes, so it doesn't seem to be a linear progress on a big scale, maybe there are only some areas that need work, that have big gaps in between them.
UPDATE2: Okey, big disappointment, the numbers are back to very small again (2012-11-07_0720)
lseek(4, 52174548992, SEEK_SET)         = 52174548992
read(4, "\374\312\22\\\325\215\213\23\0357U\222\246\370v^f(\312|f\212\362\343\375\373\342\4\204mU6"..., 4096) = 4096
lseek(4, 46603526144, SEEK_SET)         = 46603526144
write(4, "\370\261\223\227\23?\4\4\217\264\320_Am\246CQ\313^\203U\253\274\204\277\2564n\227\177\267\343"..., 4096) = 4096

so either e2fsck goes over the data multiple times, or it just hops back and forth multiple times. Or my assumption that those numbers are bytes is wrong.
UPDATE3: Since it's mentioned here
http://forums.fedoraforum.org/showthread.php?t=282125&page=2
that you can testisk while e2fsck is running, i tried that, though not with a lot of success. When asking testdisk to display the data of my partition, this is what I get:
TestDisk 6.13, Data Recovery Utility, November 2011
Christophe GRENIER <email@example.com>
http://www.cgsecurity.org
 1 P Linux                    0   4  5 45600  40  8  732566272
Can't open filesystem. Filesystem seems damaged.

And this is what strace currently gives me (2012-11-07_1030)
lseek(4, 212460343296, SEEK_SET)        = 212460343296
read(4, "\315Mb\265v\377Gn \24\f\205EHh\2349~\330\273\203\3375\206\10\r3=W\210\372\352"..., 4096) = 4096
lseek(4, 47347830784, SEEK_SET)         = 47347830784
write(4, "]\204\223\300I\357\4\26\33+\243\312G\230\250\371*m2U\t_\215\265J \252\342Pm\360D"..., 4096) = 4096

UPDATE4: (2012-11-08_0800) Okey, so the e2fsk process failed after something over 78 hours (thats what gparted wrote) and when I tried to make gparted save the details, it stopped responding, took 100% cpu time of one of my cores for a few minutes, and then crashed printing this line in the console:
/usr/sbin/gpartedbin: symbol lookup error: /usr/lib/x86_64-linux-gnu/gio/modules/libgioremote-volume-monitor.so: undefined symbol: g_mutex_lock

It crashed before it let me chose a location to save the details, so it didn't even start writing those details to a file. So I've got nothing but a quck glimps at about 5 lines of the e2fsck output which stated something about damaged inodes it was repairing. My guess is that the output of e2fsck was that extremly long that gparted couldn't handle it and crashed when it tried.
This is the strace output of the gparted-bin process in its last minute of running right up until it failed:
http://pastebin.ubuntu.com/1341922/
Now I rebooted my notebook, and I was positively surprised to see this:
[    1.368032] usb 2-1: new high-speed USB device number 2 using ehci_hcd
[    1.501581] usb 2-1: New USB device found, idVendor=0bc2, idProduct=3320
[    1.501585] usb 2-1: New USB device strings: Mfr=2, Product=3, SerialNumber=1
[    1.501588] usb 2-1: Product: Expansion Desk
[    1.501590] usb 2-1: Manufacturer: Seagate
[    1.501592] usb 2-1: SerialNumber: NA4J4N6K
[    1.503691] usbcore: registered new interface driver uas
[    1.504736] Initializing USB Mass Storage driver...
[    1.504822] scsi5 : usb-storage 2-1:1.0
[    1.504898] usbcore: registered new interface driver usb-storage
[    1.504900] USB Mass Storage support registered.
...
[    2.504756] scsi 5:0:0:0: Direct-Access     Seagate  Expansion Desk   070B PQ: 0 ANSI: 6
...
[   13.319905] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[   13.320764] sd 5:0:0:0: [sdb] Write Protect is off
[   13.320768] sd 5:0:0:0: [sdb] Mode Sense: 43 00 00 00
[   13.321644] sd 5:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
[   13.322524] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[   19.563252]  sdb: sdb1
[   19.564818] sd 5:0:0:0: [sdb] 732566645 4096-byte logical blocks: (3.00 TB/2.72 TiB)
[   19.566944] sd 5:0:0:0: [sdb] Attached SCSI disk
...
[  105.080095] EXT4-fs (sdb1): warning: mounting unchecked fs, running e2fsck is recommended
[  105.086041] EXT4-fs (sdb1): mounted filesystem with ordered data mode. Opts: (null)

So he managed to mount the filesystem again, and it looked alright at first glance, but as recommended by the dmesg output above, I started to run e2fsck again, but this time manually without gparted as intermediate:
kaefert@blechmobil:~$ sudo e2fsck -v -p /dev/sdb1
/dev/sdb1 wurde nicht ordnungsgemäß ausgehängt, Prüfung erzwungen.
/dev/sdb1: Doppelter oder unzulässiger Block in Gebrauch!
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294954142 for Den Eintrag in der Liste belegter Blöcke verdoppeln
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294960577 for Den Eintrag in der Liste belegter Blöcke verdoppeln
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294902002 for Den Eintrag in der Liste belegter Blöcke verdoppeln
/dev/sdb1: Mehrfach beansprucht Block(s) in Inode 86114492: 4538368 3365377 3365378 3365379 3365380 ...
... << endless number of inodes, like millions of inodes, didn't count them though ;) >> ...
55455 9455456 9455457 9455458 9455459 << this is the end of the list >>
/dev/sdb1: (es gibt 6 Inodes, die doppelte/defekte Blocks enthalten.)

/dev/sdb1: Datei /Recordings/.../MVI_8559.MOV (Inode #86114492, Modifikationszeitpunkt Sat Mar 24 20:23:54 2012)
  hat Block Nr.413455 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
/dev/sdb1:  /Recordings/.../MVI_8563.MOV (Inode #86114496, mod time Sat Mar 24 20:23:54 2012)
/dev/sdb1:

/dev/sdb1: UNERWARTETE INKONSISTENZ; fsck MANUELL AUSFÜHREN
    (d.h. ohne -a oder -p Option)

So I'm gonna do just that, start without the -p parameter now. Since the e2fsck run above just took about 2 hours, I think I'll give you another update in about 2 hours.
kaefert@blechmobil:~$ sudo e2fsck -v /dev/sdb1
e2fsck 1.42.4 (12-Jun-2012)
/dev/sdb1 enthält ein fehlerhaftes Dateisystem, Prüfung erzwungen.
Durchgang 1: Prüfe Inodes, Blocks, und Größen

Doppelter Blocks gefunden... starte Scan nach doppelten Block.
Durchgang 1B: Suche nach doppelten/defekten Blocks
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294954142 for Den Eintrag in der Liste belegter Blöcke verdoppeln
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294960577 for Den Eintrag in der Liste belegter Blöcke verdoppeln
ext2fs_test_block_bitmap wurde eine unzulässige Blocknummer übergeben #4294902002 for Den Eintrag in der Liste belegter Blöcke verdoppeln
Mehrfach beansprucht Block(s) in Inode 86114492: 4538368 3365377 3365378 3365379 3365380 ... 9455459
Durchgang 1C: Prüfe Verzeichnisse nach Inodes mit doppelten Blocks.
Durchgang 1D: Gleiche doppelte Blocks ab
(es gibt 6 Inodes, die doppelte/defekte Blocks enthalten.)

Datei /Recordings/.../MVI_8559.MOV (Inode #86114492, Modifikationszeitpunkt Sat Mar 24 20:23:54 2012)
  hat Block Nr.413455 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8563.MOV (Inode #86114496, mod time Sat Mar 24 20:23:54 2012)
multiply claimed block map<j>? ja
clone_file_block: interner Fehler; dup_blk für 4538368 wurde nicht gefunden

clone_file_block: interner Fehler; dup_blk für 4538368 wurde nicht gefunden

Datei /Recordings/.../MVI_8563.MOV (Inode #86114496, Modifikationszeitpunkt Sat Mar 24 20:23:54 2012)
  hat Block Nr.413455 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8559.MOV (Inode #86114492, mod time Sat Mar 24 20:23:54 2012)
Duplizierte Blocks bereits neu zugeordnet bzw. geklont.

Datei /Recordings/.../MVI_8571.MOV (Inode #86114504, Modifikationszeitpunkt Sat Mar 24 22:09:56 2012)
  hat Block Nr.244958 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8575.MOV (Inode #86114508, mod time Sat Mar 24 22:09:56 2012)
multiply claimed block map<j>? ja
clone_file_block: interner Fehler; dup_blk für 7999488 wurde nicht gefunden

and now the pattern of the first extremly long run of e2fsck seems to repeat. The strace output looks the same and the gkrellm representation of the disk usage also (see below). and its been about 2 hours since the last output which I've posted above.
gkrellm representation of the disk usage http://kaefert.is-a-geek.org/misc/e2fsck_disk_usage_pattern_gkrellm.png
UPDATE5: (2012-11-08_2130) Okey, so e2fsck has already been running for about 12 hours again and at least 10 of those since the last line I've posted above was printed. I'm afraid this will again take 80 hours to finish (or fail) like it did the first time I saw this pattern.
UPDATE6: (2012-11-09_0653) I've added a few new lines in the console output of my 3rd e2fsck run above (he asked a second question, and now it's back to the pattern described below the output and visualized by that gkrellm screenshot.
UPDATE7: (2012-11-11_1839) Soooo.. It finished. Here are the last few lines of what it printed:
Die Anzahl Verzeichnisse ist falsch für Gruppe #20192 (0, gezählt=1).
Repariere<j>? ja
Die Anzahl freier Inodes ist falsch für Gruppe #20576 (8192, gezählt=8143).
Repariere<j>? ja
Die Anzahl Verzeichnisse ist falsch für Gruppe #20576 (0, gezählt=3).
Repariere<j>? ja
Die Anzahl freier Inodes ist falsch für Gruppe #21472 (8192, gezählt=8182).
Repariere<j>? ja
Die Anzahl Verzeichnisse ist falsch für Gruppe #21472 (0, gezählt=1).
Repariere<j>? ja
Die Anzahl freier Inodes ist falsch (183148563, gezählt=183026594).
Repariere<j>? ja

/dev/sdb1: ***** DATEISYSTEM WURDE VERÄNDERT *****

121950 Inodes sind in Benutzung (0.07%)
    1244 nicht zusammenhängende Dateien (1.0%)
      30 nicht zusammenhängende Verzeichnisse (0.0%)
         # von Inodes mit ind/dind/tind Blöcken: 0/0/0
         Erweiterungstiefe Histogramm: 121817/126
184589222 Blöcke werden benutzt (25.20%)
0 ungültige Blöcke
       4 große Dateien

  119828 reguläre Dateien
    2114 Verzeichnisse
       0 zeichenorientierte Gerätedateien
       0 Blockgerätedateien
       0 Fifos
       9 Verknüpfungen
       0 symbolische Verknüpfungen (0 schnelle symbolische Verknüpfungen)
       0 Sockets
--------
  121397 Dateien

I had to put something on the letter "j" to answer those millions of questions.
And since I did not believe him that its really clean now, I ran it a 4th time, and e2fsck admitted that not everything was right, and he still left himself things todo:
kaefert@blechmobil:~$ sudo e2fsck -f -y -v /dev/sdb1
e2fsck 1.42.4 (12-Jun-2012)
Durchgang 1: Prüfe Inodes, Blocks, und Größen

Doppelter Blocks gefunden... starte Scan nach doppelten Block.
Durchgang 1B: Suche nach doppelten/defekten Blocks
Mehrfach beansprucht Block(s) in Inode 86114492: 4538368 4405248
<< ... removed millions of entries of the same pattern here ... >>
11648685 11648686
Durchgang 1C: Prüfe Verzeichnisse nach Inodes mit doppelten Blocks.
Durchgang 1D: Gleiche doppelte Blocks ab
(es gibt 6 Inodes, die doppelte/defekte Blocks enthalten.)

Datei /Recordings/.../MVI_8559.MOV (Inode #86114492, Modifikationszeitpunkt Sat Mar 24 20:23:54 2012)
  hat Block Nr.413455 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8563.MOV (Inode #86114496, mod time Sat Mar 24 20:23:54 2012)
multiply claimed block map? ja

clone_file_block: interner Fehler; dup_blk für 4538368 wurde nicht gefunden

clone_file_block: interner Fehler; dup_blk für 4538368 wurde nicht gefunden

Datei /Recordings/.../MVI_8563.MOV (Inode #86114496, Modifikationszeitpunkt Sat Mar 24 20:23:54 2012)
  hat Block Nr.413455 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8559.MOV (Inode #86114492, mod time Sat Mar 24 20:23:54 2012)
Duplizierte Blocks bereits neu zugeordnet bzw. geklont.

Datei /Recordings/.../MVI_8571.MOV (Inode #86114504, Modifikationszeitpunkt Sat Mar 24 22:09:56 2012)
  hat Block Nr.244958 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8575.MOV (Inode #86114508, mod time Sat Mar 24 22:09:56 2012)
multiply claimed block map? ja

clone_file_block: interner Fehler; dup_blk für 7999488 wurde nicht gefunden

clone_file_block: interner Fehler; dup_blk für 7999488 wurde nicht gefunden

Datei /Recordings/.../MVI_8575.MOV (Inode #86114508, Modifikationszeitpunkt Sat Mar 24 22:09:56 2012)
  hat Block Nr.244958 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_8571.MOV (Inode #86114504, mod time Sat Mar 24 22:09:56 2012)
Duplizierte Blocks bereits neu zugeordnet bzw. geklont.

Datei /Recordings/.../MVI_3598.MOV (Inode #86376840, Modifikationszeitpunkt Thu Aug 23 21:14:34 2012)
  hat Block Nr.45835 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../SomeFile.psd (Inode #86376844, mod time Thu Aug 23 21:14:34 2012)
multiply claimed block map? ja

clone_file_block: interner Fehler; dup_blk für 345554931 wurde nicht gefunden

clone_file_block: interner Fehler; dup_blk für 345554931 wurde nicht gefunden

Datei /Recordings/.../SomeFile.psd (Inode #86376844, Modifikationszeitpunkt Thu Aug 23 21:14:34 2012)
  hat Block Nr.45835 doppelte Block(s), gemeinsam genutzt mit 1 Datei(en):
    /Recordings/.../MVI_3598.MOV (Inode #86376840, mod time Thu Aug 23 21:14:34 2012)
Duplizierte Blocks bereits neu zugeordnet bzw. geklont.

Durchgang 2: Prüfe Verzeichnis Struktur
Durchgang 3: Prüfe Verzeichnis Verknüpfungen
Durchgang 4: Überprüfe die Referenzzähler
Durchgang 5: Überprüfe Gruppe Zusammenfassung

/dev/sdb1: ***** DATEISYSTEM WURDE VERÄNDERT *****

121950 Inodes sind in Benutzung (0.07%)
    1244 nicht zusammenhängende Dateien (1.0%)
      30 nicht zusammenhängende Verzeichnisse (0.0%)
         # von Inodes mit ind/dind/tind Blöcken: 0/0/0
         Erweiterungstiefe Histogramm: 121816/126
184589222 Blöcke werden benutzt (25.20%)
0 ungültige Blöcke
       4 große Dateien

  119827 reguläre Dateien
    2114 Verzeichnisse
       0 zeichenorientierte Gerätedateien
       0 Blockgerätedateien
       0 Fifos
      11 Verknüpfungen
       0 symbolische Verknüpfungen (0 schnelle symbolische Verknüpfungen)
       0 Sockets
--------
  121952 Dateien

So this makes  me think, I have no way of getting a clean filesystem state without formatting this disk, am I right? I've started a 5th run of e2fsck, and I would bet on it again finding some problems just as the 4th run above did, although the output of the 3rd run looked like he was happy with his result and terminated himself.
I'll give you another update when the 5th run finished.
UPDATE8: (2012-12-12_1736)
In parallel to posting my progress here, I've described my problem in mails I've sent to the mailing-list firstname.lastname@example.com --> and Theodore Ts'o has read my mails there, and helped me out. I've sent him a compressed e2image -Q /dev/sdb1 image of that disk (metadata) and he gave me these commands
debugfs -w /dev/sdb1
debugfs: clri <86114492>
debugfs: clri <86114504>
debugfs: clri <86376840>
debugfs: quit

to run, which made the next e2fsck run really quick and gave me a clean filesystem state again. I've lost a few files, but most of the stuff is still where it was before the problems started. And I did not have any problems with the disk since.
And here's my kernel version and my e2fsck version from back then (copied from a mail to Ted):
kaefert@blechmobil:~$ uname -a
Linux blechmobil 3.2.0-3-amd64 #1 SMP Thu Jun 28 09:07:26 UTC 2012
x86_64 GNU/Linux

kaefert@blechmobil:~$ sudo e2fsck -V
e2fsck 1.42.4 (12-Jun-2012)
        Benutze EXT2FS Library version 1.42.4, 12-Jun-2012

(times are in CET)
Comment: uname -a, please :)
Answer: I notice that over 47% of your CPU used is "niced" (i.e. running at slower than normal priority).  Could this be the fsck process?  If so, I might suggest that you renice it to at least normal priority.  This could be the reason for the slowness.
Comment: well as I understood it this low priority will make the kernel give the processor time slots first to processes or threads with higher priority, and afterwards to the processes with lower priority. Since the other processes all take up nearly no cpu time, this priority thing shouldn't matter to much. When I look at top I see that the e2fsck process always gets between 90 and 100% of one core. I'm guessing that e2fsck is not multithreaded, or at least not started that way, therefore it can't do more than 100% of one CPU-core.
Answer: uname -a, please :)
I guess it's Theodore Tso's bug in kernel 3.x: https://lkml.org/lkml/2012/10/23/690
Comment: I've added an update to my question, which also contains the kernel version. I don't know if I've been effected by that same bug, I don't recognise the error messages that are cited there.