Ambiguity within apply

Question: I have a problem with ambiguity in the following code while using the apply function. It is based on the stackoverflow question here.
1) I have a helper class, because templated functions as pointers are not allowed:
template<typename TT, class...Ts>
struct selector_helper
{
    static TT doSelect(Ts&&... params)
    {
        return iSelectable<Ts...>::select<TT>(std::forward<Ts>(params)...);
    }
};

I tried to run the apply function, but run into problems. I tried following two codes but no one with success:
2.1) error: apply: none of the 2 overloads could convert all the argument types
boost::tuple<Ts...> tpl;
return apply<T, Ts...>(selector_helper<T, Ts...>::doSelect, tpl);

2.2) here I get two errors:

Error    2   error C2782: 'Ret apply(Ret (__cdecl *)(Args...),boost::tuples::tuple &&)' : template parameter 'Args' is ambiguous
Error    3   error C2782: 'Ret apply(Ret (__cdecl *)(Args...),const boost::tuples::tuple &)' : template parameter 'Args' is ambiguous
boost::tuple<Ts...> tpl;
return apply(selector_helper<T, Ts...>::doSelect,   tpl);

edit: more explanation:
Both examples are runned within select method, which is in a class:
class database
{
    template<typename T, typename...Ts>
    T select_(const std::string& sql)
    {
        // apply examples
    }
};

And called here:
database db;
User result = db.select_<User, int, std::string, std::string>
    ("select id, email, name from credentials_tbl limit 1");

What did I miss?
here is a full example, I hope it contains everything:
(when running with Microsoft Visual Studio 2013 I get the same errors)
// apply_test.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <boost/noncopyable.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/tuple/tuple.hpp>

using namespace boost;

/* apply methods from https://stackoverflow.com/questions/687490/how-do-i-expand-a-tuple-into-variadic-template-functions-arguments#answer-6454211 */

// ------------- UTILITY---------------
template<int...> struct index_tuple{};

template<int I, typename IndexTuple, typename... Types>
struct make_indexes_impl;

template<int I, int... Indexes, typename T, typename ... Types>
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...>
{
    typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type;
};

template<int I, int... Indexes>
struct make_indexes_impl<I, index_tuple<Indexes...> >
{
    typedef index_tuple<Indexes...> type;
};

template<typename ... Types>
struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...>
{};

// ----------UNPACK TUPLE AND APPLY TO FUNCTION ---------

template<class Ret, class... Args, int... Indexes >
Ret apply_helper(Ret(*pf)(Args...), index_tuple< Indexes... >, tuple<Args...>&& tup)
{
    return pf(forward<Args>(get<Indexes>(tup))...);
}

template<class Ret, class ... Args>
Ret apply(Ret(*pf)(Args...), const tuple<Args...>&  tup)
{
    return apply_helper(pf, typename make_indexes<Args...>::type(),
        tuple<Args...>(tup));
}

template<class Ret, class ... Args>
Ret apply(Ret(*pf)(Args...), tuple<Args...>&&  tup)
{
    return apply_helper<Ret, Args...>(pf, typename make_indexes<Args...>::type(), forward<tuple<Args...>>(tup));
}

/* end of apply methods */

/* class iSelectable */
template <typename...> struct iSelectable;

template<class...Ts>
class iSelectable
{
public:

    template<typename T>
    static T select(Ts&&...params)
    {
        return T(std::forward<Ts>(params)...);
    }

};

/* selector_helper */
template<typename TT, class...Ts>
struct selector_helper
{
    static TT doSelect(Ts&&... params)
    {
        return iSelectable<Ts...>::select<TT>(std::forward<Ts>(params)...);
    }
};

class postgres_database_impl : private boost::noncopyable
    , public boost::enable_shared_from_this<postgres_database_impl>
{
public:

    template<typename T, typename...Ts>
    T select_(const std::string& sql)
    {

            boost::tuple<Ts...> tpl;

            /* This is where my errors occur: */

            return apply(selector_helper<T, Ts...>::doSelect, tpl);

    }

};

typedef boost::shared_ptr<postgres_database_impl> DatabaseImpl;

class Database : private boost::noncopyable
{
public:

    template<typename T, typename...Ts>
    T select_(const std::string& sql)
    {
        return impl_->select_<T, Ts...>(sql);
    }

private:
    DatabaseImpl impl_;

};

class User : public iSelectable < int, std::string, std::string >
{
public:

    User(int id, const std::string& name, const std::string& surname)
    {
        /* only for testing purposes */
        std::cout << name << ", ";
        std::cout << name << ", ";
        std::cout << surname << std::endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    Database db;
    User result = db.select_<User, int, std::string, std::string>
        ("select id, email, name from credentials_tbl limit 1");

    return 0;
}

Comment: Please provide a complete example. What are the template arguments of your tuple?
Comment: added more explanation
Comment: You need to provide a self contained example. You never specify what `apply` is, to begin with. I just spent ~10 minutes reading that linked question+answers and still can't work out what you are most likely referring to.
Comment: I provided a full example.
Comment: @Felix I just noticed the update. I've updated my answer too
Answer: Regardless of context of the question, I'd usually expect the selector_helper type to look more like:
template <typename...> struct iSelectable;

template<typename TT>
struct selector_helper
{
    template<class... Ts>
    static TT doSelect(Ts&&... params) {
        return iSelectable<Ts...>::template select<TT>(std::forward<Ts>(params)...);
    }
};

Note the extra  template qualification on the nested select template. If select is a type (how can we know) you might need typename too: Where and why do I have to put the "template" and "typename" keywords?
UPDATE
Looking at the more complete example, this is exactly the problem. The template arguments to do_select are explicitly specified:
return apply(selector_helper<T, Ts...>::doSelect, tpl);

This won't work, because it suppresses template argument deduction, and the signature is forced to

User (&)(int&&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&&)

Of course, though the tuple is actually

boost::tuples::tuple<int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, ...>&

You can see there will be conflicting types deduced for Args....
I would actually simplify this by being less specific:
template <class Ret, class Tuple, class... Args, int... Indexes>
Ret apply_helper(Ret (*pf)(Args...), index_tuple<Indexes...>, Tuple&& tup) {
    return pf(std::forward<Args>(get<Indexes>(std::forward<Tuple>(tup)))...);
}

template <class Ret, class Tuple, class... Args>
Ret apply(Ret (*pf)(Args...), Tuple&& tup) {
    return apply_helper(pf, typename make_indexes<Args...>::type(), std::forward<Tuple>(tup));
}

This compiles already
Live On Coliru
// apply_test.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <boost/noncopyable.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/make_shared.hpp>

#define _TCHAR char
using namespace boost;

/* apply methods from
 * https://stackoverflow.com/questions/687490/how-do-i-expand-a-tuple-into-variadic-template-functions-arguments#answer-6454211
 */

// ------------- UTILITY---------------
template <int...> struct index_tuple {};

template <int I, typename IndexTuple, typename... Types> struct make_indexes_impl;

template <int I, int... Indexes, typename T, typename... Types>
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...> {
    typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type;
};

template <int I, int... Indexes> struct make_indexes_impl<I, index_tuple<Indexes...> > {
    typedef index_tuple<Indexes...> type;
};

template <typename... Types> struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> {};

// ----------UNPACK TUPLE AND APPLY TO FUNCTION ---------
    template <class Ret, class Tuple, class... Args, int... Indexes>
    Ret apply_helper(Ret (*pf)(Args...), index_tuple<Indexes...>, Tuple&& tup) {
        return pf(std::forward<Args>(get<Indexes>(std::forward<Tuple>(tup)))...);
    }

    template <class Ret, class Tuple, class... Args>
    Ret apply(Ret (*pf)(Args...), Tuple&& tup) {
        return apply_helper(pf, typename make_indexes<Args...>::type(), std::forward<Tuple>(tup));
    }

/* end of apply methods */

/* class iSelectable */
template <typename...> struct iSelectable;

template <class... Ts> struct iSelectable {
    template <typename T> static T select(Ts &&... params) { return T(std::forward<Ts>(params)...); }
};

/* selector_helper */
template <typename TT, class... Ts> struct selector_helper {
    static TT doSelect(Ts &&... params) { return iSelectable<Ts...>::template select<TT>(std::forward<Ts>(params)...); }
};

class postgres_database_impl : private boost::noncopyable,
                               public boost::enable_shared_from_this<postgres_database_impl>
{
  public:
    template <typename T, typename... Ts> T select_(const std::string &sql) {
        boost::tuple<Ts...> tpl { -123, "fame", "something" };

        /* This is where my errors occur: */
        return apply(selector_helper<T, Ts...>::doSelect, tpl);
        return {123, "name", "something"};
    }
};

typedef boost::shared_ptr<postgres_database_impl> DatabaseImpl;

class Database : private boost::noncopyable {
  public:
    template <typename T, typename... Ts> T select_(const std::string &sql) { return impl_->select_<T, Ts...>(sql); }

  private:
    DatabaseImpl impl_ = boost::make_shared<postgres_database_impl>();
};

class User : public iSelectable<int, std::string, std::string> {
  public:
    User(int id, std::string name, std::string surname)
        : id(id), name(std::move(name)), surname(std::move(surname)) {
    }

  private:
    int id;
    std::string name;
    std::string surname;

    friend std::ostream& operator << (std::ostream& os, User const& user) {
        return os << user.id << ", " << user.name << ", " << user.surname << "\n";
    }
};

int main() {
    Database db;
    User result =
        db.select_<User, int, std::string, std::string>("select id, email, name from credentials_tbl limit 1");

    std::cout << "Result: " << result << "\n";
}

Output:
Result: -123, fame, something

I think I see a lot of opportunity for further simplification, but to be honest I would need to know more about the goal to embark on that journey.

Ambiguity within apply


rails cancan custom actions

Question: I'm trying to prevent editors of various items from being able to publish their own works using cancan but it doesn't work as expected. Everything else so far works perfectly.
For example:
can :publish, [Article, Review] do |doc|
  doc.user != @user
end

View
<% if can? :publish, @review %>

I followed the docs for setting up a custom action but so far I have not had any success.
https://github.com/ryanb/cancan/wiki/Custom-Actions
ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    @user = user || User.new # for guest
    @user.roles.each { |role| send(role) }

    if @user.roles.size == 0
      can :read, :all #for guest without roles
    end
  end

  def author
    can :manage, [Article, Review] do |doc|
      doc.try(:user) == @user
    end
    can :submit, [Article, Review]
  end

  def editor
    can :manage, [Article, Review]
    can :publish, [Article, Review] do |doc|
      doc.user != @user
    end
  end

  def admin
    can :manage, :all
    can [:submit, :publish, :reject], [Article, Review]
  end
end

Answer: I think that you're looking to do this
cannot :publish, [Article, Review], :user_id => @user.id

This is saying that the user cannot publish an Article or Review if the creator of the article is them.
For example, in my app, I have where a user that is logged in can create new Questions. Users can manage their own questions and users can vote on questions. However, a user cannot vote on their own question. Does this sound familiar? :)
  can [:new, :create], Question
  can :manage, Question, :user_id => user.id
  can :vote, Question
  cannot :vote, Question, :user_id => user.id

rails cancan custom actions


Using Nginx as Webserver and Reverse proxy

Question: I am trying to setup Nginx as a reverse proxy and webserver together. and I'm having issues in trying to understand how I can do it.
Let's assume I am using the default Symfony2 nginx configuration
(http://symfony.com/doc/current/cookbook/configuration/web_server_configuration.html):
server {
    server_name example.com www.example.com;
    root /var/www/project/web;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /app.php$is_args$args;
    }
    # DEV
    # This rule should only be placed on your development environment
    # In production, don't include this and don't deploy app_dev.php or config.php
    location ~ ^/(app_dev|config)\.php(/|$) {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
    }
    # PROD
    location ~ ^/app\.php(/|$) {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS off;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/app.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

I want to add a configuration so the Nginx will also function as a reverse proxy. and not only a webserver.

Do I need to add to the same configuration file the proxy_pass, proxy_cache, etc.. configurations?
Do I need to set a configuration for a specific routes? or to disable them?
If for example if I don't want the route /app_dev.php/abc to be cached? what do I need to do?
Comment: Add an `upstream` block for the destination you want to forward to, then add a second `server` block with the proxy configuration inside (the minimal config is `location / { proxy_pass http://; }`.
Comment: but this configuration is my Webserver as well.. so what do you mean by redirect?
Answer: Basically nginx is proxy server. Its capabilities include proxy HTTP, HTTPS, IMAP, POP3, SMTP and other protocols. For HTTP(S) proxy, the backend can be either FastCGI server like PHP-FPM or another web server.
For FastCGI backend like you need fastcgi module. For example, you need to define the backend with fastcgi_pass. For proxying another website, you need HTTP proxy module. You need to use direction like proxy_pass, proxy_cache to control the behaviour of this module.

Do I need to add to the same configuration file the proxy_pass, proxy_cache, etc.. configurations?

YES

Do I need to set a configuration for a specific routes? or to disable them?

For example, you need proxy the the specific URL www.example.com/myawesomeapp, then use location to match the URL
location /myawesomeapp {
    proxy_pass http://<upstream_block_name>;
    ... other parameter ...;
}

If for example if I don't want the route /app_dev.php/abc to be cached? what do I need to do?

Use proxy_cache_bypass. You can set by if directive like this tutorial.


Meaning of '4:1 (3:0)' as score in football (World Cup match)

Question: I'm looking at Fifa data on the France vs Mexico World Cup match in 1930, the score is presented as 4:1 (3:0). Looking at the 'goals scored' section I see 5 goals have been scored, all of them in regular playing time. So my question is, what does the the (3:0) mean?
I figured it might be something related to do with how points are awarded in the group stage of the tournament, but another match (USA vs Belgium) which was also part of the group match has score '3:0 (2:0)' so I don't think that's it.
Answer: The parenthetical shows the halftime score.  This is confirmed from the list of scores:

Lucien LAURENT (FRA) 19'
Marcel LANGILLER (FRA) 40'
Andre MASCHINOT (FRA) 43'
Juan CARRENO (MEX) 70'
Andre MASCHINOT (FRA) 87'


How to convert a matrix saved as a struct to matrix

Question: I downloaded a Matrix from https://sparse.tamu.edu/Embree/ifiss_mat, after loading this file i noticed that the matrix is stored as a struct containing 3 arrays of row indices, column indices and data. In this particular case represented as a struct containing Problem.A.ir, Problem.A.jc, Problem.A.data.
I am only used to having the matrix readily available as Problem.A, is there a way to convert from this struct to a 'normal' matrix?
Answer: Having looked at the data and the description in the link you gave, it appears to me that this particular dataset follows the following pattern:

data are the values at the nonzero locations
ir are row indices IN ZERO-BASED FORM, corresponding to nonzero locations (same size as data)
jc is a helper vector telling you IN ZERO-BASED FORM when one column of row-indices stops and the next one starts in the ir vector

So, e.g. the first 20 entries in ir are:
0  1  2  33  34  35  66  67  68  0  1  2  33  34  35  66  67  68  0  1

The first 3 entries in jc are:
0  9  18

This means that in the first column, assuming ZERO-INDEXING, rows 0 1 2 33 34 35 66 67 68 (i.e. ir[0:8] have nonzero data (taken from data[0:8] respectively).
Then, in the second column, rows 0 1 2 33 34 35 66 67 68 (i.e. ir[9:17]) have nonzero data (taken from data[9:17] respectively.
Then you have to adjust all that by 1, to convert it to the ONE-BASED-INDEXING supported by matlab/octave.
Once you've processed all of this, you'll be able to create an array of i,j,v triplets corresponding to row, column, and value, for all the nonzero values in your dataset (i.e. the 3,599,932 entries in data). Then, you can pass these i, j, and v vectors into sparse, along with the dimensions of the matrix (96,307 x 96,307 according to the website), to create your sparse matrix.
Unfortunately I don't think there is a specific function that recognises this format and produces the matlab/octave equivalent sparse matrix for you. You'll have to come up with code to do this manually. This shouldn't be too hard though.

PS. Note that many of the other fields in the problem struct are in fact text, but for some reason it was encoded as ascii numbers. To retrieve the actual text you need to pass it into char, e.g. char(Problem.notes)


Who'll win the baseball game when two really good teams play?

Question: Our team is playing another team that wins 70% of its games. Our team is pretty good but wins only 60% of its games. If these teams have never played before and they've played equally hard opponents, what is the chance our team will be victorius? I think I solved it by comparing the game to flipping coins, but was looking for an answer a little more mathematical or rigorous.
My approach is based on flipping coins. The other team's "coin" comes up heads 70% of the time (and 30% tails) and our team's "coin" comes up heads 60% of the time (and 40% tails). If I flip the coins many times and disregard the outcomes when both coins are heads or both coins are tails, I would expect 18% of the flips our team's coin would have a head and their team's coin would be a tail (0.6*0.3); and 28% of the flips the other team would get a head and our team a tail (0.7*0.4). Thus, our team would be expected to win 39% of the games (0.18/(0.18+0.28) and the other team 71%.
I thought I'd ask if this makes sense and for a more mathematical approach. Thank you
Comment: $39\%+71\%=110\%$
Comment: [To win, ya gotta give 110%](https://www.youtube.com/watch?v=6b5IpCpeb0M)
Comment: There is no rigid answer to this, just about any result is possible.  Of course you can add assumptions and come up with an answer that way.   [here](https://math.stackexchange.com/questions/1358700/an-average-of-probabilities) is a related question with some discussion.
Comment: Note:  I'd say that the model you propose is too lopsided.  In practice, I (for one) would not expect such an overwhelming advantage to the stronger team.  You could, of course, vary matters by saying that the teams split the $HH$ and $TT$ cases event, or something like that.  As I say, it is not difficult to come up with possible models.
Answer: There is no correct answer, but the theory underlying Elo ratings in chess implicitly uses odds-ratios.  This is similar to what you have done with your flipping argument. One way of applying it here might look like:

If the first team has a probability of winning against a standard team of $70\%$ and losing of $30\%$ then the odds of it winning are $\frac73$
If the second team has a probability of winning against a standard team of $60\%$ and losing of $40\%$ then the odds of it winning are $\frac64=\frac32$
If you divide one by the other, you get an odds-ratio of $\frac{14}{9}$ in favour of the first team which might suggest its probability of beating the second team could be around $\frac{14}{23} \approx 60.87\%$
Similarly you get an odds-ratio of $\frac{9}{14}$ for the second team which might suggest its probability of beating the first team could be around $\frac{9}{23} \approx 39.13\%$

Those are the same results as your method should give.  It has a degree of transitivity when applied to more than two teams, which is an attractive property though could only really be justified or not empirically.


Garbage DNS record

Question: nslookup returns 2 IP addresses for one of the clients in my network:
<code>Server:  dc.mynet.local
Address:  192.168.43.1

Name:    fileserver.mynet.local
Addresses:  192.168.43.2
          192.168.45.2
</code>
My DNS server have no "192.168.45.2" record, at least I can't find it. This garbage record, I suppose, is the reason of the "RPC server not available" error that I often get when trying to connect TO FILESERVER via RDC. This error can be temporarily fixed by restarting DNS client service on FILESERVER.
How to clean this record out of the DNS server?
Comment: If 192.168.45.2 isn't valid then simply delete it.
Comment: Two A records is valid. If you want help with your DNS server you'll have to tell us what server you're using and post relevant details, such as the configuration that describes any local DNS entries.
Comment: I know that multiple A records may be valid. But not in my case. I use DNS server that is running on the DC (Windows 2003 Server virtual machine on the Hyper-V host). This server has 2 network adapters: 192.168.43.1 (connected to LAN) and 192.168.45.1 (connected to Hyper-V internal network). FILESERVER is a virtual machine on the same Hyper-V host and has 2 similar network adapters with adresses 192.168.43.2 and 192.168.45.2. No DNS server is specified for 192.168.45.2, but it was specified before (that's how the 2nd A record appeared).
Comment: Well it's strange but now I can see the corresponding A record in DNS server console. I deleted it, and now nslookup shows only one address for FILESERVER. Hard to tell where the record came from as it surely was lacking before.
Comment: I believe I got it. I did everything (clearing DNS cache, restarting DNS server) except refreshing DNS server console contents by pressing F5. That's why I didn't see the records that actually were there.
Answer:
Open the DNS Manager MMC snap-in (dnsmgmt.msc)
Connect to DNS server on DC.mynet.local (if running dnsmgmt.msc from a machine other than DC.mynet.local)
Expand 'DC'
Expand 'Forward Lookup Zones'
Select 'mynet.local'
Right-click and delete record with the name 'FILESERVER', type 'Host (A)' and data '192.168.45.2'
Flush local DNS cache (ipconfig /flushdns) and retest
Comment: As I said, there's no record with the name 'FILESERVER', type 'Host (A)' and data '192.168.45.2' there. That's what the problem is.
Comment: Sorry, I misunderstood.

What forwarders does the DNS server on DC use?

Have you cleared the cache for the DNS server on DC?
Comment: Also run dig so you can get more information than nslookup offers.
Comment: No forwarders, no root servers. It's an internal DNS server.
Comment: That doesn't make sense... all your workstations should have only the DC(s) set as DNS servers... if there are no forwarders on the DNS server it will have nowhere to recurse to provide clients records for names it is not authoritative for (e.g. serverfault.com). Did you actually check the properties of the DNS server?
Comment: All my clients have the DC as the first DNS server and the DNS forwarder on the Internet gate as the second DNS server. It allows them to have access to the Internet even if the DNS server on the DC is unavailable (not an often case but still).

Garbage DNS record


IntelliJ 13 select Groovy SDK from Gradle dependencies

Question: For my Android project I want to run a test HTTP server for my integration tests.  I've created a Configuration and have written a task to run my Groovy script the sets up the HTTP server
configurations {
  stubs {
    description = "Classpath for HTTP server for stubbed data"
    visible = false
  }
}

dependencies {
  compile "com.android.support:support-v13:+"

  stubs "org.codehaus.groovy:groovy:2.3.4"
  stubs "com.github.tomakehurst:wiremock:1.46"
}

When I edit the Groovy script IntelliJ tells me that the Groovy SDK hasn't been configured.
How can I have IntelliJ use the Groovy SDK that is part of the stubs Configuration? I can't create a Groovy SDK configuration using the Gradle fetched libraries as IntelliJ tells me that the Groovy distribution is broken because the version number can't be determined.
Am I forced to have to download the distribution manually?
Answer: The solution was to separate out the project for the HTTP server into a separate project and use Gradle's multiproject's ability to set up the Android tests to depend on the HTTP server being started.  Because the separate project is a Groovy project, IntelliJ reads the Groovy version to use from the project's dependencies and all is well.
dependencies {
  compile "com.android.support:support-v13:+"

  stubs project(":integration-server")
}

/*
 * The android plugin defers creation of tasks in such a way that they can't be accessed eagerly as usual
 * @see http://stackoverflow.com/questions/16853130/run-task-before-compilation-using-android-gradle-plugin
 */
gradle.projectsEvaluated {
  connectedAndroidTest.dependsOn(":integration-server:startBackgroundServer")

  // Note: finalizedBy is still @Incubating
  connectedAndroidTest.finalizedBy(":integration-server:stopBackgroundServer")
}

integration-server/build.gradle
apply plugin: "groovy"
apply plugin: "spawn"

dependencies {
  compile "org.codehaus.groovy:groovy:2.3.4"
  compile "org.codehaus.groovy:groovy-ant:2.3.4"
  compile "com.github.tomakehurst:wiremock:1.46"
}

task startBackgroundServer(type: SpawnProcessTask, dependsOn: "build") {
  def cp = sourceSets.main.runtimeClasspath.asPath

  command "java -cp $cp server"
  ready "Started email@example.com:8089"
}

task stopBackgroundServer(type: KillProcessTask)

To prevent the Gradle build blocking I'm using a Gradle Spawn Plugin to launch the HTTP server in the background.


Exibir popup ao fechar página

Question: Olá. Gostaria de saber um código para exibir um formulário como popup quando o usuário for fechar a página. Ou seja, aquele momento em que ele leva o cursor para cima do navegador. Pois a página foi feita pela ferramenta RD.
Formulário em questão:
https://forms.rdstation.com.br/formulario-071734d1611046a89c8d
Código do formulário:

Agradeço quem puder ajudar.
Answer: Você pode utilizar o evento mouseleave no objeto document.
Esse evento é disparado toda vez que um usuário deixa uma área, nesse caso, a área do site.

new RDStationForms('formulario-071734d1611046a89c8d-html', 'UA-113131074-1').createForm();

document.onmouseleave = function() {
  console.log("oushe");
  document.querySelector("#overlay").style.setProperty("display", "flex", "important")
}
html, body {
  height: 100%;
  width: 100%;
}

#overlay {
  display: none !important;
  height: 100%;
  width: 100%;
  background:rgba(0,0,0,.5);
  display: flex;
  align-items: center;
  justify-content: center;
  position:absolute;
}

Insira o cursor aqui

Você também pode utilizar o evento beforeunload. Ele será disparado quando o navegador tiver prestes a fechar toda a página.
window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "Já vai sair?";

  e.returnValue = confirmationMessage;
  return confirmationMessage;
});

O erro que aparece é problema no JavaScript externo.
Comment: Obrigado Valdeir. Respondi em baixo pois não consegui formatar corretamente.
Comment: @Maicon atualizei minha resposta. Adicionei um exemplo com o formulário.
Comment: Ótimo @Valdeir. Veja como ficou.. http://materiais.financiatudo.com.br/teste. Apenas na minha página a popup não aparece como sobreposição com botão de fechar. Você consegue me ajudar com isso?
Comment: @Maicon editei minha resposta. Adicionei o `position` no CSS e alterei de `block` para `flex` ao levar o cursor para fora da página.

Exibir popup ao fechar página


Change URL of site, server and folder remains the same

Question: I want access an old site on a new domain. The server and folder remains the same. I have pointed the new domain to the old Drupal site and updated settings.php to include
$base_url = 'http://www.newurl.com';

I can access the site, but all links in the theme and in the control panel point to http://oldurl.com. I can navigate around the site by manually altering each URL to reflect the new domain.
I'm under the impression that updating base_url should work, and take effect immediately. Have I missed something?
Comment: Are the links in a WYSIWYG? Those aren't dynamic. You need something like https://www.drupal.org/project/pathologic to help if they are
Comment: No, it's every link on the site, front-end and back-end.
Answer: Seems the website was coded using absolute paths, which is not really good practice from Drupal coding standard's perspective. Please read the discussion on Absolute or relative URLs?. Your case is covered by the accepted answer:

When moving a site from dev > staging > production a Wordpress site's
  URLs and image references have to be replaced in the DB, this can
  create an absolute mess.

Though Wordpress is mentioned, that concerns any type of websites, including Drupal.
Anyway, to address the issue you need to do two things:

Look for and replace all the instances of your old domain in the active theme's template folder. This is easier part as any decent text editor has Find&Replace feature.

Check the website again and if everything is working then you are lucky. If not proceed to the second step.

Search and replace all the instances of your old domain in the database tables. You can do it either using drush or UI like phpMyAdmin. The query is pretty simple:
UPDATE table_name SET field_name = replace(field_name, 'old-domain', 'new-domain');

To do so you first need to figure out the tables where your old domains could be stored. Most probably those are 'node' and 'comment' tables and their last revisions, however if content types have additional custom fields then more tables are involved. You could perform quick search for the old domain in the database to find all the tables where it is stored.
If step 2 is involved, then I would also suggest, using the opportunity, to turn all your paths from absolute to relative. In that case, you would run:
`UPDATE table_name SET field_name = replace(field_name, 'old-domain/', '/');`

instead.
I hope this helps.
Comment: When you say "the website was coded with absolute paths", what do you mean exactly? OP has mentioned that this is for every link in the site, front and back end, and not just (or even at all) those in a WYSIWYG or link field. I'm struggling to think of how that could have been coded, would you mind elaborating?
Comment: Thanks for your reply. There are two enabled themes - one is the Drupal Seven theme, the other is custom but I can't actually see any files relating to it. I would have thought that even if the theme was badly put together, the back-end links would include the correct domain specified in the configuration? It seems like a global issue - beyond any theming issues.
Comment: @Clive, I meant sometimes they use the absolute paths like `http://www.example.com/some-path-to/filename.ext` incorporating the website's domain name explicitly instead of using global variable $base_url. And that ends with exactly the same situation as OP reported.
Comment: @user83960, have you actually searched the custom theme's directories for your old domain name? You can do it by changing the working directory to the theme's directory and launch the `grep -Ril "old_domain" .` command. You should, because if templates contain absolute paths using your old domain, then just specifying the correct domain in the configuration won't help.
Comment: But who's "they"? Those links are generated by the system, not a person
Comment: According to https://en.oxforddictionaries.com/definition/they `It is now generally accepted in contexts where it follows an indefinite pronoun such as anyone, no one, someone, or a person, as in anyone can join if they are a resident and each to their own.` Anyway, I meant whoever built the theme could've hardcoded the old domain in templates. If not there then it's definitely about the database. What OP described above obviously tells the old domain is used somewhere and s/he needs to find and remove it.
Comment: @AltaGrade, I can't see there is a directory associated with the theme. Aside from seven, there are 3 other themes installed but disabled, and I can see the directories for them. Then there's another directory named "engines", which has 1 file - phptemplate.engine. I exported the DB (a whopping 396MB - is that normal for Drupal? Wordpress equivalent is 30MB) and replaced 1,450 instances of the old domain with the new. Should I be able to import and expect anything to work?
Comment: Seven is administrative theme, so besides it you should have at least one more active theme on `admin/appearance`. If you don't that means you have not enabled any theme yet, so do it. If you don't have your own custom theme then go with bartik.
Comment: But then the fact you have replaced 1,450 instances of old domain name in the database shows the problem might not be about your theme. The database size is quite normal, there are Drupal websites with DB size much larger than that. Just try to upload the database with replaced domain name and see what happens.


Maximum Likelyhood Estimator (MLE) vs. Bias

Question: If we use the MLE methhod to find the estimator of the variance we get:
$\hat\sigma ^2 = \frac{\sum(x_i - \mu)^2}{n}$
Where we can plug the MLE estimator for $\mu$ and get:
$\hat\sigma ^2 = \frac{\sum(x_i - \bar x)^2}{n}$
But we know that this estimator is biased, and in order to correct for the bias, we need to use $n-1$ instead of $n$:
$S ^2 = \frac{\sum(x_i - \bar x)^2}{n - 1}$
My question is why do we care more for bias than for the likelyhood?
Subquestion - how much is the unbiased estimator less likely to appear given an (arbitrary) sample ?
Update:
I don't see how this is a duplicate. I understand that this estimator is biased. I completely agree with the answer given in the linked "duplicate". I'm asking something completely different. I'm asking why do we care more about correcting the bias, than we care about maximizing the likelihood.
In the normal example, the MLE estimators are what maximizes the likelihood function of our sample. So say we got $(\hat\mu, \hat\sigma^2) = (100, 25) $ for n of 100. Then correcting the bias will give us $(100, 25*\frac{100}{99} = 25.25)$ which will not maximize the likelihood. i.e. it is not the maximum anymore.
So why do we care about fixing the bias more than maximizing the likelihood? I guess the answer is that the likelihood is less important than the bias, though I wonder - why?
Comment: A simple remark: if $\hat\theta$ is the MLE for $\theta$, $h(\hat\theta)$ is the MLE for $h(\theta)$, while, if $\hat\theta$ is unbiased for $\theta$, $h(\hat\theta)$ is most often biased for $h(\theta)$.
Answer: I do not understand the subquestion.
Regarding the question, it is not that we care more for bias that for the likelihood. The ML principle has important advantages. In order to compare estimates, however, we may want to restrict ourselves to a given class: without such restriction, there may be no such thing as a best estimator.
One such class is that of unbiased estimators. It makes sense to correct the bias of the MLE so that we can compare with other unbiased estimators in search, for example, of a minimum variance unbiased estimator.
Comment: I see, this is indeed a good reason, as all the minimum variance theorems require unbiased estimators.
Comment: So to conclude - we rather give up a bit of likelihood, and get in return an estimator which is unbiased and has minimum variance.
Comment: I tried to simulate it now, calculating both the unbiased estimator and the biased estimator for a normal distribution with n=1000, and I did it 100 times and calculated the variance of both estimators - it was consistently bigger for the unbiased estimator. I ran this a few times and always the same result. So how can this be?
Comment: It also makes sense that the unbiased estimator will give bigger variance, as the results spread out more.


How do I toggle the enabled status of a radio button group in jQuery?

Question: I have a group of radio buttons with a class of "laser2" on each button.  I have a checkbox with an ID of "duaL-laser".  I am trying to toggle the availability of the radio button group with the checkbox.  I know the class toggling works (for display purposes).  Here is my code.

This works when I check the checkbox.  But when I uncheck the checkbox, the radio buttons remain enabled.  Even though the if statement is true at the bottom of the code.  What gives?
Comment: Can you post a fiddle for this?
Comment: That fiddle appears to be missing some HTML.
Comment: No worries.  Once you create the new fiddle you need to click update and copy/paste the new URL over here.
Answer: Try changing this:
if ($('#dual-laser').attr('checked', false)) {
        $('.laser2').attr('disabled', true);
    }

to this:
if ($('#dual-laser').prop('checked')) {
        $('.laser2').attr('disabled', true);
    }

Right now you are setting that attribute and I suspect you want to get it.
UPDATE
Also, should the above statement be inside of your click event?  Right now it's only being executed on document ready.  Something like this:
$('#dual-laser').click(function() {
        $('div#power-listing2').toggleClass('disable');
        //$('.laser2').removeAttr('disabled');
        $('.laser2').attr('disabled', !$(this).prop('checked'));
    });

UPDATE 2
Here is a simplified fiddle that should do what you need: http://jsfiddle.net/pHJ5u/3/
Comment: Nope.  They're still enabled after I uncheck the box.
Comment: Your updated code works fine.  I was on the wrong track.  Thanks, Abe!


Convert file located in relative path into a Django File object

Question: I have a file located at below relative path in my source code:
docs/Shootsta_Videographer_critical_info.pdf

I want to convert this file into a Django File object. Please help.
Answer: The docs for Django https://docs.djangoproject.com/en/2.2/ref/files/file/ states that the File constructor accept a Python file object.
So something like this:
from django.core.files import File
django_file = File(open('<base_dir>/docs/Shootsta_Videographer_critical_info.pdf'))


Converting to Fin Type in Coq

Question: Can anyone tell me why the following projection function in COQ doesn't work?
Require Import Vector.
Require Import Fin.

Definition Proj {n:nat}{p:nat}(x:t p+{(exists m : nat, n=p+m)}):=
match x with
inleft y => y
|_  => F1
end.

I get the following error:
Error:
In environment
n : nat
p : nat
x : t p + {(exists m : nat, n = p + m)}
e : exists m : nat, n = p + m
The term "F1" has type "t (S ?6 (* [n, p, x, e, e] *))"
 while it is expected to have type "t p".

On the other hand, using concrete values for p works fine:
Require Import Vector.
Require Import Fin.

Definition Proj {n:nat}(x:t 3 + {(exists m : nat, n=3+m)}):=
match x with
inleft y => y
|_  => F1
end.

Eval compute in  (Proj (of_nat 2 3))  = FS (FS F1): t 3.

Comment: What do you expect the return type to be? What should you get back when `p` is `O`?
Answer: I'm assuming that you want Proj to return a value of type t p. That is impossible for p = 0 (because t 0 is the empty set), and that's why you cannot implement Proj for arbitrary p. If you extend you function to take a proof that p is not equal to 0, then you can implement it as follows. Read Adam's CPDT Chapter on Dependent Types to understand what is going on here.
Definition Proj {n:nat} {p:nat} (x:t p+{(exists m : nat, n=p+m)}) : p <> 0 -> t p :=
  match x with
  | inleft y => fun _ => y
  | _  => match p with
          | 0 => fun h => False_rect _ (h eq_refl)
          | S _ => fun _ => F1
          end
  end.

Converting to Fin Type in Coq


Token to get the last component of [node:url]

Question: I'm using [node:url:relative] but my path has multiple parts /content-type/node-title . I would like to get only the node-title part.
Alternatively, a token that give me the node title transliterate would be fine.
Answer: [node:title] will give you the node title.


How to use Rsync to copy only specific subdirectories (same names in several directories)

Question: I have such directories structure on server 1:

data

company1

unique_folder1
other_folder
...

company2

unique_folder1
...

...

And I want duplicate this folder structure on server 2, but copy only directories/subdirectories of unique_folder1. I.e. as result must be:

data

company1

unique_folder1

company2

unique_folder1

...

I know that rsync is very good for this.
I've tried 'include/exclude' options without success.
E.g. I've tried:
rsync -avzn --list-only --include '*/unique_folder1/**' --exclude '*' -e ssh firstname.lastname@example.com:/path/to/old/data/ /path/to/new/data/

But, as result, I don't see any files/directories:
receiving file list ... done
sent 43 bytes  received 21 bytes  42.67 bytes/sec
total size is 0  speedup is 0.00 (DRY RUN)

What's wrong? Ideas?

Additional information:
I have sudo access to both servers. One idea I have - is to use find command and cpio together to copy to new directory with content I need and after that use Rsync. But this is very slow, there are a lot of files, etc.
Answer: I've found the reason. As for me - it wasn't clear that Rsync works in this way.
So correct command (for company1 directory only) must be:
rsync -avzn --list-only --include 'company1/' --include 'company1/unique_folder1/***' --exclude '*' -e ssh email@example.com:/path/to/old/data/ /path/to/new/data

I.e. we need include each parent company directory. And of course we cannot write manually all these company directories in the command line, so we save the list into the file and use it.

Final things we need to do:
1.Generate include file on server 1, so its content will be (I've used ls and awk):
+ company1/
+ company1/unique_folder1/***
...
+ companyN/
+ companyN/unique_folder1/***

2.Copy include.txt to server 2 and use such command:
rsync -avzn                                        \
      --list-only                                  \
      --include-from '/path/to/new/include.txt'    \
      --exclude '*'                                \
      -e ssh firstname.lastname@example.com:/path/to/old/data/    \
      /path/to/new/data

Comment: Nevermind, I figured it out. I was doing `folder**` instead of `folder/***`. You need the third asterisk when you use a slash after the directory name. The two asterisks and no slash method also works, but is less precise, because it will also match peer folders with the same base name.
Comment: Regarding three a asterisks; The Rsync man page defines... `trailing "dir_name/***" will match both the directory (as if "dir_name/" had been specified) and everything in the directory (as if "dir_name/**" had been specified).  This behavior was added in version 2.6.7`
Comment: Also consider this http://unix.stackexchange.com/a/42691/37431 if you want to exclude top most directory
Comment: Hey Andron, Is there a reason you used the triple asterisks? I've experimented with both two and three and I can't tell a difference. And I'm using this technique to backup some files right now, thanks for posting it.
Comment: @ChadvonNau hmm, not sure why I've used `***`. In [RSync docs](http://linux.die.net/man/1/rsync) I see `use '**' to match anything, including slashes`. So maybe 2 asterisks is enough. But I think that 3 is better :)
Comment: Are `-n` and `--list-only` for testing here? I'm an rsync newbie and had no idea why the command does nothing but listing.
Answer: If the first matching pattern excludes a directory, then all its descendants will never be traversed. When you want to include a deep directory e.g. company*/unique_folder1/** but exclude everything else *, you need to tell rsync to include all its ancestors too:
rsync -r -v --dry-run                       \
    --include='/'                           \
    --include='/company*/'                  \
    --include='/company*/unique_folder1/'   \
    --include='/company*/unique_folder1/**' \
    --exclude='*'

You can use bash's brace expansion to save some typing. After brace expansion, the following command is exactly the same as the previous one:
rsync -r -v --dry-run --include=/{,'company*/'{,unique_folder1/{,'**'}}} --exclude='*'

Comment: Thanks @yonran, as you can see below - 'include list' is too huge. That's why the list was placed in a file (please see an accepted answer below). And thanks for "bash's brace expansion" - need to give it a try.
Comment: This answer is valid, although, if we're using bash features, then we're entering a grey area :) In this case, it's worth noting that a simple `shopt -s globstar; rsync -avn --relative /sourcepath/./**/a destpath` will do.
Answer: An alternative to Andron's Answer which is simpler to both understand and implement in many cases is to use the --files-from=FILE option. For the current problem,
rsync -arv --files-from='list.txt' old_path/data new_path/data

Where list.txt is simply
company1/unique_folder1/
company2/unique_folder1/
...

Note the -r flag must be included explicitly since --files-from turns off this behaviour of the -a flag. It also seems to me that the path construction is different from other rsync commands, in that company1/unique_folder1/ matches but /data/company1/unique_folder1/ does not.
Comment: This method was a lot easier for me, as it allowed the use of `find` to generate the list of directories to include.
Answer: For example, if you only want to sync target/classes/ and target/lib/ to a remote system, do
rsync -vaH --delete --delete-excluded --include='classes/***' --include='lib/***' \
      --exclude='*' target/ user@host:/deploy/path/

The important things to watch:

Don't forget the "/" from the end of the pathes, or you will get a copy into subdirectory.
The order of the --include, --exclude counts.
Contrary the other answers, starting with "/" an include/exclude parameter is unneeded, they will automatically appended to the source directory (target/ in the example).
To test, what exactly will happen, we can use a --dry-run flags, as the other answers say.
--delete-excluded will delete all content in the target directory, except the subdirectories we specifically included. It should be used wisely! On this reason, a --delete is not enough, it does not deletes the excluded files on the remote side by default (every other, yes), it should be given beside the ordinary --delete, again.
Comment: This answer doesn't actually answer the question. The suggested `--include='***/dirName/'` doesn't work as intended.
Comment: thanks. That is a good idea. But in my case, you can see that I had the same subdirectory name in X different directories. So, I'm not sure if that is possible to do with your idea.
Comment: @Andron It is true. I think, the `--include` paramlist should be modified, maybe to an `--include='***/dirName/'` or similar. I did not test it, but my example is from a real, tested, working deploy script.
Comment: @Marcus I am used it in early 2019, and I am using it now, and it works as intended. Could you please explain, exactly what won't work by you?
Comment: Sample follows; nothing is synced: ```cd /tmp;

mkdir -p data/company{1,2}/{unique_folder1,other_folder};
touch data/company{1,2}/{unique_folder1,other_folder}/testfile;

tree data;

rsync -vaH --include='***/unique_folder1/' --exclude='*' data/ dest```
Comment: I am getting nothing to sync as well using the exact example above just modified for my directories.  Any ideas?


I cant solve this problem... Im 17 and I dont know calculus. The topic that this problem was in is Polynomial zeros.

Question: Write the polynomial $p$. $p$ is a 3rd degree polynomial. $p(x)$ is divisible by $(x-0,5)$. $p(x)$ is divisible by $(x+0,5)$. $p(x)$ is divisible by $(x+2)$. When we divide $p$ by $(x-2)$ we get a remainder $-3$.
I know that if polynomial p is divisible polynomial q we can write $p(x) = (x)\cdot q(x) + r(x)$ where $k(x)$ is a quotient and $r(x)$ is the remainder.
I don't know how to solve the problem however.
Any help would be appreciated.
Thank you.
Answer: If the polynomial is divisible by $(x-\frac 12)$, $(x+\frac 12)$, $(x-2)$ and has degree 3, you have that
$$
p(x) = c(x-\frac 12)(x+\frac 12)(x+2)
$$
The constant $c$ can be computed from the last condition...
Comment: Wow that was fast! Thank you for your help.
Answer: According to your information, we know that :
$$P(X)=a(X-0.5)(X+0.5)(X+2) $$
Then you can use your last information to get $a$ :
$$P(X)=Q(X)(X-2)-3 $$
So you know that $P(2)=-3 $
$$a\times 1.5\times 2.5\times 4 =-3$$
So you get :
$$\boxed{a=-0.2} $$
Comment: Thank you very much!


How to simulate network latency/ artificially add latency to a network?

Question: I need to make a Windows program using .NET, C, C# that adds latency to data moving through that computer on a network. Basically, if I have a room full of computers, I want to this program to turn a computer into a node that delays the information that moves through it as if that info is going from one computer to another 500 miles away. This is to test programs in a lab as if they are being used over the internet. The program has to handle udp, tcp, ipv4, ipv6, and pim multicast connections.
I've been digging through the .NET System.Net API trying to figure out which API tools would be helpful, but I'm not really sure where to begin. Do I need to to make a client program and a server program and use System.Net.Sockets for tcp and udp connections and ip endpoints for ipv4 and ipv6?
If possible, I'd like to make one program that you run on one computer that adds latency to everything running through it. Is this possible/feasible?
I wish I had more to present to get more specific answers, but I'm just not sure where to begin on this one.
Comment: 500 miles away... so... 2ms delay? :)
Comment: Sure, or thousands of miles, or however great a distance that would cause up to 1000ms delay.
Comment: 1000ms - nowhere on earth
Comment: Satellites are pretty far.
Answer: There are a number of products that already do this, out there:that sit in the stack and allow you to tweaks line speeds, latency, packet Loss, duplication of packets and so on.
The dummynet project
SoftPerfect Connection Emulator
Comment: I'm looking through the dummynet project to see how it works. I need to make my own program that is similar to dummynet, but with only latency functionality. Thank you for your response.
Comment: Could you explain to me what stack you're referring to? Is it a network stack or have something to do with the windows network layer?

Also, how would I access the stack with C or C# (what libraries/classes/methods would help me do this)?

Any and all information you mind sharing is much appreciated.
Comment: The ISO Model Layers 3-5 are typically the ones you can hook into. Typically you access these API's through device drivers or SDK's if you really want to get at all the finer details.


What are the 14 different types of saxophone?

Question: I heard my saxophone instructor say that there are 14 sizes of saxophone. But, I've only heard of 4 (soprano, alto, tenor, baritone). What are the other 10 types?
Comment: saxaboom?  ;)  https://www.youtube.com/watch?v=cLmCJKT5ssw
Comment: @b3ko I want one of those things :)
Answer: From Yamaha there were 14 types, but according to Yamaha now only 5 are in wide spread use: soprano, alto, tenor, baritone, and bass.

https://www.yamaha.com/en/musical_instrument_guide/saxophone/structure/structure002.html

I tried to dig deeper to verify the claim of 14, but I could not find anything conclusive. Some sources claim the number comes from a patent that Sax obtained, but even that cannot be easily confirmed. In fact, I found this article about the  saxophone patents: McBride, The Early Saxophone in Patents 1838-1850 Compared.
There is a image online which is supposed to be from Sax's original patent...

https://www.selmer.fr/histdetail.php?id=3
https://i2.wp.com/www.thesax.info/photoblog/wp-content/uploads/2013/03/1846-1VV1.jpg

...no definitive claim could be made from just that picture, nor does it give names.
You can easily Google for a list of names of instruments in the saxophone family and find page like...

https://en.wikipedia.org/wiki/Saxophone

...but I'm not going to attempt making a list here, because I can't confirm anything other than the well known list of five above. At least with those I have seen them all with my own eyes!
Comment: @tim There are also straight alto saxophones. I would call these variations, but not different sizes, so they wouldn't change the list.
Comment: That could be augmented by one - the straight soprano, as opposed to the sax-shaped usual.
Comment: Saxe patented what he designed;  many more (of absurd range) were built later on.
Comment: @Tim "sax shaped usual"?  I've never seen a soprano saxophone that wasn't straight.
Comment: @phoog - there are more than a few on the market. I used to play in a jazz band where the sax player had a standard tenor, and a 'bent' soprano, both obviously in the same transposition, so easier to interchange.
Answer: There are 9 Saxophones in the primary family (marked with a dagger (†)). And there are as many as 15 types of saxophones, depending on how you define the word. The first four in the list are the most common. Instruments marked with an asterisk (*) are not always considered true saxophones and any one of them may not have been considered one of the 14 by the instructor.
The list is as follows:
Tenor† - In the key of B♭ (one octave below) - sounding range from A♭2 to E5

Alto† - In the key of E♭ - sounding range from D♭3 to A♭5

Soprano† - In the key of B♭ - sounding range from B♭3 to G♭6

Image Source
Baritone† - In the key of E♭ (one octave below) - sounding range from C2 to A4

Image Source
Sopranissimo†* - in the key of B♭ (one octave above) - sounding range from B♭4 to D♭7

Image Source
Bass† - Key of B♭ (two octaves below) - Sounding range B♭1 to F4 (I think)

Image Source
Sopranino† - In the key of E♭ - sounding range from D♭4 to A♭6

Image Source
Contrabass† - In the key of E♭ (two octaves below) - sounding range D♭1 to A♭3 (I think)

Image Source
Tubax* - Available in E♭, B♭, or C (all two octaves below) - sounding range of E♭ (the lowest) model is the same as Contrabass - D♭1 to A♭3 (I think)

Image Source
C Melody - Key of C (one octave below) - sounding range B♭2 to F5

Image Source
Slide Saxophone*

Image Source
Saxello*

Image Source
Connosax (aka Conn-O-Sax)*

Subcontrabass† - Key of B♭ (three octaves below!) - Sounding range B♭0 to F3 (I think)

Mezzo Soprano - Essentially a Soprano sax in F - Sounding range E♭3 to B♭5 - This may not have been counted separately from the soprano sax by the instructor
Comment: I'm not sure this accurately answers the OPs question because he asked about different sizes, not variations. For instance, the Tubax is a variation on the bass sax, the Saxello is a brand name version of the soprano, and the Conn-O-Sax is a variation on the F mezzo soprano that was only produced for a couple years. Similarly, the Slide Sax was a novelty instrument from the 1920s that was never widely played (and it was the same size as a soprano). The Sopranissimo sax is smaller than a sopranino, but it is only made by one company and goes by the brand name Soprillo sax.
Comment: This is a great example of a question with no really definitive answer.  Exactly what counts as a saxophone?
Comment: @ScottWallace - moot point. I wonder if my *xaphoon* would be counted..?
Comment: This answer would be a lot more useful if you explained what the nonobvious ones are, such as "tubax", "saxello," "connosax" .
Comment: I agree that slide saxes don't really count.  That's a mechanism, not a range.
Comment: @Peter there are several different slide saxophones - in fact i thnk they were featured in a question on this site 6 months ago.  I recal one model was purely trombone-ish  (total bore length changes) while another opens or closes holes on the lower body as it slides over the upper body (which doesn'thave holes)
Comment: @CarlWitthoft Cool. I was only familiar with the latter type: https://www.dornpub.com/SaxjPDF/slidesax.pdf
Comment: @Peter OP asks about *size* and *types*. Variations fits there, doesn't it?
Comment: @Tim - I actually thought that too about my xaphoon.  But seeing as the xaphoon is cylindrical in bore and not conical, I think it would rather count as one of the 317 kinds of clarinet...
Comment: @ScottWallace - the original xaphoons, made from bamboo, would be very slightly conical. Only 317? Looks like another question needs posing...
Comment: @Tim - yeah, mine's a bit conical too, but not enough to disturb its acoustical cylindricity.  It plays an octave lower than a flute- or a conical reed instrument like the sax does.  I have another candidate for a sax: a sort of medieval soprano sax of wood with no keys.  Sounds very much like a soprano sax.
Answer: Today, saxophones are either in Eb or Bb, but C and F saxophones were produced in the early 20th century, so some of the standard horns had C and F counterparts. The most common of these was the C melody sax, which was a C version of the soprano that was popular because it used to read piano music (without transposition). There was also an F mezzo-soprano that has been used by a few performers (https://en.wikipedia.org/wiki/Mezzo-soprano_saxophone).
Some other obscure ones include sopranino (smaller than a soprano), contrabass sax (bigger than bass), and even the sub-contrabass sax (which was used by the Nuclear Whales Saxophone Orchestra).
There are other types that have been specially produced, like this G mezzo-soprano: http://thesax.info/blog/jessen-g-mezzo-soprano/
Comment: I believe the number 14 comes from Adolphe Sax's original vision of the saxophone family; that is: sopranino, soprano, alto, tenor, bari, and bass, each in Eb/Bb versions and C/F versions. Not all of these versions were ever actually mass produced though.
Answer: Cecil Forsyth's orchestration a manual from the 1910's mentions 7 varieties of saxophone (Sopranino, Soprano, Alto, Tenor, Baritone, Bass, Contrabass), in 2 series (a military series in E♭/B♭, and an orchestral series in F/C):
This is a total of 14 (7×2) types of saxophone, and I bet this is how your instructor is coming up with that figure.
But, even in this hundred-year-old book the "extreme" Sopranino and Contrabass are only really mentioned to complete the set; they aren't at all common.  The entire F/C "orchestral series" has also basically died out these days.

From Cecil Forsyth's Orchestration (1914, 1st ed., England)

Plate VI (facing p. 167):

p. 167:

Five varieties of this instrument are made in this country {England}.  Like the Saxhorns they are built alternately in E♭ and B♭.  These five varieties are, in the list given below, numbered 2, 3, 4, 5, 6.  Two other instruments are used in France and Belgium.  They are both "extreme" instruments, one in the treble, the other in the bass.  We may add them to our list as Nos. 1 and 7.  The Complete catalogue is then as follows:
[(1) Sopranino in E♭.]
 (2) Soprano in B♭.
 (3) Alto in E♭.
 (4) Tenor in B♭.
 (5) Baritone in E♭.
 (6) Bass in B♭.
[(7) Contrabass in E♭.]
The whole series of theses seven military instruments, alternately in E♭ and B♭, is also reduplicated abroad by orchestral Saxophones alternately in F and C.  It must be mentioned, however, that even abroad No. 7 (the "Contrabass") scarcely exists except as a workshop-curiosity.   The Bass Saxophone in B♭ (No. 6) is as heavy an instrument as any Wind-player would care to tackle.  The "Contrabass," therefore, has been omitted entirely from the list of these instruments given on pages 7 and 8.
The general appearance of the Saxophones can be gathered from the illustration on Plate VI.  The five instruments shown on the Plate are numbered to correspond with the list given above.
Comment: Fifteen. Let us not forget the [saxamophone](https://www.youtube.com/watch?v=21x7KObESV0).
Comment: @Aaron Or [this one](https://youtu.be/FB_JTIXkZ-Y?si=MJjbtBRIUaCgyC7w&t=26)  in V-flat.
Answer: i understand there supposedly 14 but i found more...Sopranino, soprano, curved soprano, mezzo soprano, alto, c-melody, tenor, bari, bass, contrabass, and sub-contrabass, tubax, slide, saxello, connosax,  saxophones. that doesnt include some of the variations in key


Show email reminder if receiver didn't respond for certain time

Question: I have one task such that make leave request form using c# in windows application. The steps are as follows.

After filling all the fields, mail should send to the manager.
If manager didn't see that email or he didn't give any response for one day, then we have to show a reminder or notification such that "waiting for response" (for example).

For the first step I know how to send an email through SMTP. But how to know that manager responds or not for that thread and showing notification (it may be alert message or windows notification). For all these process should I use work flows?
Any best ways to do it?
Is it better to implement in asp.net or windows application. I am planning to do it windows application.
Answer: If the manager didn't see the email can be accomplished by requesting a read receipt and checking for that. It's not foolproof, as the manager can simply decline to return the receipt, but it's the best you have.
He didn't give a response for one day is much harder though. The only way I can see to do this is funnel all communication back through your application as a man-in-the-middle. What I mean is to set the reply-to address to something your application has access to, then once your application reads it and records the response, the program forwards the email to the intended recipient. This way you can watch the response go by and forward it on to the intended recipient. This does mean you need your application to be running all the time, probably as a service.
The only other option is to forgo email altogether and use your application to read and respond to the requests. This way you have access to everything and can just keep a timestamp in your database.
Comment: oh..i think it may be little bit hard then. Need to do some R & D... Do you know any links to refer the above concepts..
Comment: No I don't but I think Google is your friend here. The problem is email inherently uses very simple protocols so there's no built-in way to "monitor" what happens with them, rather akin to snail mail. You can send a letter certified so you know someone gets it, but the only way to know if they reply is to wait for the reply to come.
Comment: I added another sentence to see if that helps explain what I mean. The first part is called a "read receipt" or "return receipt". The second and third parts don't really require searching so much as implementing IMHO (unless you need to read up on fetching email via `POP3` or `IMAP`, that is)


How do I attach a CAPTCHA when adding the contact form to a node?

Question: I am embedding the Drupal contact page in a node. I added the following code in template.php.
function sakura_preprocess_node(&$variables) {
  $node  = $variables['node'];
  if (!empty($node)) {
    $variables['template_files'][] = "node-" . $node->nid;
  }
}

Then, I created the node-24.tpl.php template file (for the node where I add the contact form).
require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';

//no need to maintain two version of node.tpl.php
include "node-page.tpl.php";

function local_contact_page() {
  $form = contact_mail_page();
  // override default values here if you want
  // next one will select a different category
  //$form['cid']['#default_value'] = 0;
  $form['submit']['#value'] = 'Отправить';
  unset($form['copy'], $form['subject']);
  dpm($form);
  return($form);
}

function local_contact_page_submit($form_id, $form_values) {
  return(contact_mail_page_submit($form_id, $form_values));
}

function local_contact_page_validate($form, $form_state) {
  return(contact_mail_page_validate($form, $form_state));
}

print drupal_get_form('local_contact_page');

drupal_set_message($form_id);

I also enabled the CAPTCHA module with the math method. On /contact it shows the CAPTCHA, but it doesn't show it on the contact form I embebbed in the node.
How can I make the CAPTCHA appear on the node page with the contact form?
Comment: You might be looking for hook_form_alter to alter the existing form. embedding form/PHP in a node with PHP Filter module is never a good idea.
Answer: Webform module is best for creating forms and still having options that come with regular nodes. It also integrates with captcha.
What is the reason you are embedding the form in the node like that?
Comment: Because i won't use that module for just a single form :( i want to integrate captcha in the core contact form.
Comment: Can you achieve the same functionality by using blocks and showing them only on the /contact page? Why do you want to embed the contact form in a node, instead of just using the /contact page?


Pointwise convergence and Sobolev bounded

Question: If $\{f_n\}$ is a sequence of function on $\Omega$, and $\lim_{n\to\infty}f_n=f$ on $\Omega$. $\|f_n\|_{W^{k,p}(\Omega)}$ is bounded (or uniformly bounded), then whether $f$ is in $W^{k,p}(\Omega)$. If not, are there some counterexample?
Answer: Counter example in $W^{1,1}([-1,1])$
$$
    f_n(x)=\left\{
                \begin{array}{ll}
                  0 &  x\in [-1,0]\\
                  nx & x\in \left(0,\frac{1}{n}\right]\\
                  1 &  x\in \left(\frac{1}{n},1\right]\\
                \end{array}
              \right.
$$
$f_n \rightarrow \chi_{(0,1]}$ pointwise.
Comment: In your example, the $W^{1, p}$ norm is bounded only for $p\leq 1$.
Comment: missed it. You are right.
Answer: Not sure about the general case, but it's true at least when $\Omega$ is bounded, has Lipschitz boundary and $p>1$. First let $k =  1$, then a bounded sequence $\{f_n \}$ in $W^{1, p}(\Omega)$ (by passing to subsequence) converges to $g \in L^p(\Omega)$ strongly, by Rellich–Kondrachov theorem. By picking again a subsequence, we can choose $f_n \to g$ almost everwhere. Thus $f = g \in L^p(\Omega)$.
For any $i$, by weak compactness of $L^p$ space, there are $f_i \in L^p(\Omega)$ so that
$$\frac{\partial f_n}{\partial x^i} \to f_i$$
weakly in $L^p(\Omega)$. Now for any test function $\phi$, we have
$$\int_\Omega f \partial_i \phi = \lim_{n\to \infty} \int_\Omega f_n \phi = - \lim_{n\to \infty} \int_\Omega \frac{\partial f_n}{\partial x^i} \phi = -\int_\Omega f_i \phi \ .$$
Thus $f \in W^{1, p}(\Omega)$.
The general case ($k\geq 1$) follows from this one by considering $\partial^\alpha f_n \in W^{1, p}(\Omega)$, where $|\alpha| = k-1$.


Prob. 15, Chap. 4 in Baby Rudin: Every continuous open mapping of $\mathbb{R}$ into $\mathbb{R}$ is monotonic

Question: Here is Prob. 15, Chap. 4 in the book Principles of Mathematical Analysis by Walter Rudin, 3rd edition:

Call a mapping of $X$ into $Y$ open if $f(V)$ is an open set in $Y$ whenever $V$ is an open set in $X$.
Prove that every continuous open mapping of $\mathbb{R}^1$ into $\mathbb{R}^1$ is monotonic.

My effort:

Suppose $f$ is a continuous open mapping of $\mathbb{R}^1$ into $\mathbb{R}^1$. If $f$ is not monotonic, then there exist real numbers $x$, $y$, and $z$ such that
  $$x < y < z,$$
  and
  $$\mbox{ either } f(x) < f(y) \ \mbox{ and } \ f(y) >  f(z), \ \ \mbox{ or } \ \ f(x) >  f(y) \ \mbox{ and } \ f(y) < f(z). $$
Now as $f$ is continuous on the closed interval $[x, z]$ and as $[x, z]$ is a compact subset of $\mathbb{R}$, so the image $f\left( [x, z] \right)$ is also a compact --- and hence closed and bounded --- subset of $\mathbb{R}$.
Thus the set $f\left( [x, z] \right)$ has a maximum element $M$ and a minimum element $m$.
First, assume that $$x < y < z, \  \ f(x) <  f(y), \ \mbox{ and } \ f(y) > f(z). $$
  Then $$ f(y) >  \max \left\{ f(x), f(z) \right\}. \ \tag{1}$$
But in view of (1) above, we can conclude that the maximum $M$ of $f\left( [x, z] \right)$ is attained at some interior point $p$, say, of $[x, z]$.
Then we can conclude that the image set $f\left( (x, z ) \right)$ of the open set $(x, z)$ in the domain space $\mathbb{R}^1$ has a maximum element $M$ and therefore cannot be open in the codomain space $\mathbb{R}^1$; for no $\delta > 0$ can the open interval $( M-\delta, M+\delta)$ be contained in $f\left( (x, z ) \right)$, which gives rise to a contradiction.
So we assume that $$ x < y < z, \ \ f(x) > f(y), \ \mbox{ and } \ f(y) < f(z). $$
  Then
  $$f(y) < \min \left\{ f(x), f(z) \right\}. \ \tag{2}$$
  Then the minimum $m$ of the set $f \left( [x, z] \right)$ is attained at some interior point $q$, say, of $[x, z]$, which implies that the image under $f$ of the open set $(x, z)$ fails to be open because this image set contains $m$ but fails to contain the open interval $(m-\delta, m+\delta)$ for any real number $\delta > 0$, which is a contradiction.
Hence every continuous open mapping $f$ of $\mathbb{R}^1$ into $\mathbb{R}^1$ is monotonic.

Is this proof correct? If so, then what about the presentation? Is the presentation lucid enough too? If not, then where does the problem lie?
Answer: Hint: Let $a<b$. Since $f(x)$ is continuous and open, then
$$ f((a,b))=(c,d) $$
for some $c<d$. Try to show $f({a,b})={c,d}$. From this, either $f(a)=c,f(b)=d$ or $f(a)=d,f(b)=c$. Namely $f(a)<f(b)$ or $f(a)>f(b)$.
Answer: I think it has a minor problem, since this problems wants you to prove that f is strictly monotomic. If f is not strictly monotonic, we can find three points x
Comment: It seems some part of your answer is missing?


Strip first 9 characters off filename in batch file

Question: I need to strip the first 9 characters off filename in windows batch file.
The filename format that I need the characters stripped off is
0009mmdd_abcd_abcdefgh_00009_yyyymmddhhmmss.dat
I tried using the following but it does not work
setlocal enabledelayedexpansion
for /f %%a in ('dir /b *.dat') do (
  SET oldName = %%a
  SET newName = %oldName:~9%
  echo %%a
  echo %oldName%
  echo %newName%
  echo !newname!
)

The output it get is
SET oldName = 00091017_abcd_abcdefgh_00009_20141021111145.dat
 SET newName = ~9
 echo 00091017_abcd_abcdefgh_00009_20141021111145.dat
 echo
 echo
 echo !newname!
)
00091017_abcd_abcdefgh_00009_20141021111145.dat
ECHO is on.
ECHO is on.
ECHO is on.

Any help is greatly appreciated.
Comment: you know about and use delayed expansion. Just do it consequent: `set newname=!oldname:~9!` (and take out the spaces in your `set` commands).
Answer: If your real problem is to strip the string before the first underscore:
setlocal
for /f "tokens=1*delims=_" %%a in ('dir /a-d /b *.dat') do (
 echo(ren "%%a_%%b" "%%b"
)

Note: assumes that portion up to first underscore is to be deleted.
instructions merely echoed for testing purposes. change echo(ren to ren to actually do the rename.
a-d added to dir command to exclude directorynames.
Comment: Magoo, You are a genius.  Your solution worked perfectly.  Thank you all for responding quickly to my reqeust.
Answer: SET oldName = %%a
SET newName = %oldName:~9%
             ^ Space included in value
           ^   Space included in variable name

So, you are defining two variables called %oldName % and %newName %. Try with
@echo off
    setlocal enabledelayedexpansion
    for /f "delims=" %%a in ('dir /a-d /b *.dat') do (
      SET "oldName=%%a"
      SET "newName=!oldName:~9!"
      echo %%a
      echo !oldName!
      echo !newname!
    )


How can I zebra stripe a gridview that uses jquery tablesorter?

Question: I have an asp.net GridView that I use the tablesorter on:
  $(document).ready(function() {
     $("[id$='_myGridView']").tablesorter({ sortList: [[0, 0]] });
  });

How can I apply zebra striping that re-stripes when re-sorting?
Edit:  As @Chetan Sastry pointed out, it's as simple as:
  $(document).ready(function() {
     $("[id$='_myGridView']").tablesorter({ sortList: [[0, 0]], widgets: ['zebra'] });
  });

Comment: http://stackoverflow.com/questions/979669/alternate-row-coloring-in-jquery
Answer: Have you seen the zebra widget in tablesorter plugin? This says it is part of plugin core - http://tablesorter.com/docs/example-widgets.html
Comment: Don't forget with a gridview you may need to render the  etc. for tablesorter to work, as seen in this post: http://stackoverflow.com/questions/3978990/how-can-i-use-jquery-tablesorter-with-an-asp-net-gridview
Answer: It looks like .tablesorter() applies classes of odd and even on the rows of your table. The CSS rule from the Tablesorter webpage is:
table.tablesorter tbody tr.odd td { background-color: #F0F0F6 }


drush up fails to update, though it says it deos

Question: Here's my output...
<code># drush up drupal-7.39
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182131/drupal.                                                                           [ok]
Backups were restored successfully.                                                                                [ok]
</code>
And then if I immediately try the same thing again, I see that it still doesn't think it install 7.39.   I can confirm that /user#overlay=admin/reports/updates tells me that I am still running 7.38
<code># drush up drupal-7.39 -y
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182138/drupal.                                                                           [ok]
Backups were restored successfully.
</code>
Any thoughts why I can't update Drupal.  And, in case it matters, I'm using Drupal to run CiviCRM.   And I think that is the "project" that it failed to get update data for.  But I believe I have to manually update CiviCRM by copying files and stuff, so that seems okay to me.   But perhaps I'm wrong on that.  But I can't see why, since I JUST want to patch the Drupal Core with the security update.
Answer: "Backups were restored successfully" means that Drush failed at some step, and restored your old version of Drupal over the recently updated version.  Try setting file ownership &/or permissions; run with --debug, and perhaps you will see more information about why the upgrade is failing.


Unifying polynomials

Question: Solving a combinatorial problem I find that there are $p(n)=\frac{1}{24}(5n^3+3n^2-2n)$ solutions
for even $n$ and $q(n)=\frac1{24}(5n^3+3n^2-5n-3)$ for odd $n$.
Now I would like to find a "uninomial" that coincides with $p$ for all even values
and with $q$ for all odd values.
A trivial example would be $p(n)+(\lceil\frac n2\rceil-\lfloor\frac n2\rfloor)(q(n)-p(n))$,
but I want something more specific.
I want (in this case) an expression of the form $a_3p_3^3+a_2p_2^2+a_1p_1+a_0$,
where each $p_i$ is either $n$ or $\lceil\frac n2\rceil$ or $\lfloor\frac n2\rfloor$
(and each $a_i$ is a real number).
Or, slightly more general, every $p_i^i$ may be replaced by a product of $i$ factors,
each of which is either $n$ or $\lceil\frac n2\rceil$ or $\lfloor\frac n2\rfloor$.
The specific problem is small enough to succumb to a brute force attack by a computer program,
but I am looking for a kind of mechanism.
Any ideas? Or a reference maybe? Stupid Google has never heard of a uninomial and
I seem unable to find the keywords that may trap Google into revealing a relevant location.
Answer: $$p(n)=\frac1{24}(5n^3+3n^2-2n) \text { n even}$$
$$q(n)=\frac1{24}(5n^3+3n^2-2n-3(n+1)) \text { n odd}$$
Because $(1-(-1)^n)/2=0$ if $n$ even and $(1-(-1)^n)/2=1$ if $n$ odd, we can combine $p(n)$ and $q(n)$ as:
$$f(n)=\frac1{24}\left(5n^3+3n^2-2n-\frac{3}{2}(n+1)(1-(-1)^n)\right)$$
Comment: Thanks Mike, but this is an answer in the category "$p(n)+(⌈n2 ⌉−⌊n2 ⌋)(q(n)−p(n))$" and not what I am looking for. It does not satisfy the requirements (e.g. an exponent $n$ is not allowed). Also I do not really need an answer to the example problem, but a way to attack this kind of problem in general.

Unifying polynomials


Formula to compute binary trailing zeroes of an integer

Question: I'm looking for a (simple) formula $t: \mathbb{N} \rightarrow \mathbb{N}$ to compute the number of trailing zeroes in the binary representation of a given $n \in \mathbb{N}$.
Like so:
$t(1) = t([1]_2) = 0$
$t(2) = t([10]_2) = 1$
$t(3) = t([11]_2) = 0$
$t(4) = t([100]_2) = 2$
etc.
I once found a rather complex formula back in 2016, that actually works, but is very clunky:
$t(n) = \sum_{k=1}^\infty cos( \frac{1}{2^k} \pi n) \prod_{j=1}^k cos( \frac{1}{2^j} \pi n)$
The basic idea behind this one is to sum cosines, which become $1$ at some $2^k$ and $0$ otherwise. It works, is provable by induction and I have worked with it, like e.g. here (sorry for IEEE paywall, it is just an example and not that much of importance).
However, I am still wondering, if there isn't any better or more simple way to describe $t(n)$, as the above formula is really hard to use. It also relies on non-integer functions (cosine), despite $t(n)$ being an $\mathbb{N} \rightarrow \mathbb{N}$ function.
Any ideas? Thanks in advance!
Comment: This question has apparently been discussed quite extensively here https://mathoverflow.net/questions/29828/greatest-power-of-two-dividing-an-integer
Comment: I came to a point, where I end up with t(n) being an exponent in a sum in a problem, that I'm currently working on. The series and product make it rather difficult to proceed. The specific term in question is $\sum^{2^{r+1}-1}_{i=2^r} \sum^{i}_{j=1} 4^{t(i)}$, which I found empirically to be equal to $(\sum^{r-1}_{t=0} 3 \cdot 2^{r-1-t} \cdot 2^{r-1} \cdot 4^t) + (2^r \cdot 4^r)$. I am struggling with the proof, that these two are in fact equal.
Comment: I don't want to sound rude, I'm just curious why you are looking for it .
Comment: Awesome! That indeed is the same question as mine. Thank you.
Comment: From the links within the link of @md5 I found, that the problem is called "2-adic valuation of n" or the "ruler sequence", and in fact is an entire field of research. Thanks again for the awesome pointer!
Answer: The number of trialing zeros in binary notation is the highest power of $2$ that divides the number in decimal notation.
$t(n)=\displaystyle \sum_{k=1}^\infty \left( 1-\left\lceil\left\{\frac{n}{2^k}\right\}\right\rceil\right)$ satisfies the above condition (where {} denotes the fractional part).
If $k$ is the highest power of $2$ that divides $n$, then the first $k$ terms of $t(n)$ is $1$ while the rest of the terms are $0$ so the formula for $t(n)$ gives the number of trialing zeros in binary notation.
Comment: Hmm.. For $n=4$ I get $t(4) = (1 - \lceil\frac{4}{2}\rceil) + (1 - \lceil\frac{4}{4}\rceil) + (1 - \lceil\frac{4}{8}\rceil) + ... = (1-2) + (1-1) + (1-1) + ... = -1$ (or am I missing something..?)
Comment: @jroew $\{\}$ is the denotes the fractional part (eg: $\{5.7\}=0.7)$
Comment: I see, sorry for that. Okay, makes sense now, thank you.
Still, I'm not sure if this is easier to handle, than the cosine one above. However, I'll see, if I can work with it, it indeed looks simpler, though. :)
Answer: What you are trying to compute is $\nu_2(x)$, the $2$-adic valuation of $x$, i.e. the highest exponent $\nu_2(x)$ such that $2^{\nu_2(x)}$ divides $x$ (see here).
If you like a fanciful formula you can get this one:
$$\nu_2(x) = \log_2 \left[x - \sum_{k=0}^{\lfloor \log_2{x} \rfloor}\left(\left\lfloor\frac{2x-1+2^{k+1}}{2^{k+2}}\right\rfloor - \left\lfloor\frac{2x-1+2^{k+2}}{2^{k+3}}\right\rfloor - \left\lfloor \frac{x}{2^{k+2}} \right\rfloor\right)2^k \right] + \frac{1+(-1)^x}{2}$$
For an explanation see here.
Comment: Thanks for the followup, I guess this floor-heavy formula might be even harder to handle... However, a few days after I posted the original question, I found a way to proove my formula without relying on a direct formula for the 2-adic valuation. As I wrote in a different comment, I tried to simplify a double-sum over a term having the 2-adic valuation in its exponent. Reordering the terms actually did the trick.


Which VPS configuration would be better?

Question: I currently have a VPS at HostingRails.com, and am rather disappointed with the service so I have been considering switching to linode instead. I have three rails applications (my live application, the QA version of the live application, and one redmine) running on Passenger on Apache, a phpbb installation, and one mysql database currently running on my VPS which altogether takes up about 400MB of RAM at the moment.
I am trying to figure out if it'd be better to get a 720MB node and just stick everything on there, or get two 360MB nodes and have the live site on one and the QA site and redmine on the other (in that case, would you suggest two separate databases, one for each node)? It was suggested to me that splitting up my applications would be a good idea, but I don't know if that's true; I figure that if I have one node, if the live application needs more memory, it can take out of the 360MB that probably wouldn't be fully used by my QA install and redmine.
Also, I currently have my SVN (1 active project, a couple inactive ones, two users) hosted on Dreamhost because I had paid for a plan in advance and left my SVN there instead of moving it to my VPS. Would moving SVN to linode affect your answer?
Answer: With two nodes, while you get the same amount of memory, you also get twice as much CPU time and IO tokens.
SVN could run in the same apache instance as Passenger, without hurting performance too much.
Also, you might want to consider a different setup: one database node, and one webserver node. Neither would be underutilised (apache is quite heavy, after all), and, if they were in the same datacenter, you could point both public IPs at the webserver node (Linode allow this), and let it communicate with the database node through Linode's LAN (avoiding transfer quotas).
Comment: Thanks for your response. If I was going to go with one db node and one server node, would 360MB be enough for three Rails applications (I assume that the phpbb install is pretty negligible, memorywise)? What would the benefit of having two public IPs be?
Comment: You might want two programs listening on a certain port.
For example, nginx uses less RAM than apache, so you might want to have that serving your Rails apps. However, nginx doesn't support Subversion, so you might want to have apache doing that, knowing that it will be less loaded than the public stuff (and therefore using less resources).
Comment: It's not true that with two smaller nodes, you get twice as much CPU and IO.  The reason for this is contention.  On Linode you only share your node with other nodes of the same size.  With a single Linode 1024 you are sharing CPU and IO with 19 other nodes; with two Linode 512s each one is sharing CPU and IO with 39 other nodes.  Then again, two separate nodes may still be a good idea for redundancy or even isolation.
Comment: Actually, linode endeavour to, when possible, provision nodes for the same owner on separate host machines.
Answer: From experience with providing managed hosting for a couple of Rails-based businesses, it has always proven successful to separate db and app (as fahadsadah points out).
However, I would not run Apache and nginx on the same machine, especially in a limited resources vps environment. As has been said before, Apache itself is pretty heavy, but it can handle all your passenger, svn, php needs. So I would not add nginx to the mix. After all, it's one more piece of software that needs to be maintained (configured, updated/patched, etc.).
Also, I personally tend to not host my source code within the same setup that my app runs on. I'm pretty confident in the robustness and security of our code, but if someone ever manages to find a way through the app and on the server, he'd have full access to our source as well. And your data and your code revisions is possibly the last thing you want a cracker to get his hands on...
I know it's a shameless plug, but my company offers bundled Redmine & SVN hosting under the brand Planio. There should be other services like Planio as well, so you can make a choice. My main advice is: try to delegate hosting of supportive systems to trusted external parties and focus your hosting efforts on your core thing (i.e. your app).


Expected sum of $m$ tickets.

Question: If $m$ tickets are drawn at random out of $n$ tickets which are numbered from $1$ to $n$, find the expected sum.
How to approach this problem?
Answer: hint
number of tickets drawn $\times$ expected average value of each ticket
Comment: IE: Use the Linearity of Expectation.
Comment: @GrahamKemp +1 : good assist

Expected sum of $m$ tickets.


How to use properly setFixedLengthStreamingMode(int)

Question: I'm having issues using this function. I get the length(); of the file I need to upload and i get the next error ->
Always more Bytes than expected
Exception : expected 589715 bytes but received 589840
java.io.IOException: expected 589715 bytes but received 589840
at libcore.net.http.FixedLengthOutputStream.write(FixedLengthOutputStream.java:39)
at java.io.DataOutputStream.write(DataOutputStream.java:98)
at com.androidexample.uploadtoserver.UploadToServer.uploadFile(UploadToServer.java:152)
at com.androidexample.uploadtoserver.UploadToServer$1.run(UploadToServer.java:62)
at java.lang.Thread.run(Thread.java:856)

I used this for get the size of the file
int fixedLength = (int) fileInputStream.getChannel().size();
int total = (int) sourceFile.length();

Is possible post an example of a working  setFixedLengthStreamingMode(int) correctly? I can only see problems with this method
Complete code here, yes it's for tranfer a file or some files, can be little or more than 15 Mb each, and some times I get  an out of memory in some old devices.
public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
        runOnUiThread(new Runnable() {
            public void run() {
                /*   messageText.setText("Source File not exist :"
                        +uploadFilePath + "" + uploadFileName);*/
            }
        });

        return 0;
    } else {
        try {
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            int fixedLength = (int) fileInputStream.getChannel().size();
            URL url = new URL(upLoadServerUri);
            //int total = (int) sourceFile.length();
            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setFixedLengthStreamingMode(fixedLength);
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);
            conn.setRequestProperty("mail", MAIL);
            conn.setRequestProperty("OS", "1");
            conn.setRequestProperty("LANG", "ES");
            //conn.setChunkedStreamingMode(maxBufferSize);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           buffer = new byte[bufferSize];

           // read file and write it into form...
           bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            // String serverResponseMessage = conn.getResponseMessage();

            // Log.i("uploadFile", "HTTP Response is : "
            //       + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        /*messageText.setText(msg);
                        Toast.makeText(UploadToServer.this, "File Upload Complete.",
                                     Toast.LENGTH_SHORT).show();*/
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();
        }
    }
}

Answer: You have to set it to the total number of bytes you're going to transmit. Clearly you are sending more than that. You haven't shown the relevant code so it is impossible to comment further.
Why the DataOutputStream? You don't need that just for sending a file.
EDIT: There are numerous problems with your code.
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                     + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

This is what is fouling up the fixed-length transfer mode. You haven't counted this stuff as part of the fixed-length.
// create a buffer of  maximum size

You don't need a buffer of maximum size. A buffer of 8192 bytes is perfectly adequate.
bytesAvailable = fileInputStream.available();

InputStream.available() is specifically described in the Javadoc as follows: "It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream." Fortunately you can just delete this line.
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

Unnecessary, see above. Just use new byte[8192].
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
    dos.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

Again this is all wrong. It's a misuse of available() for a start. The standard way to copy streams in Java is as follows:
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

It works for any buffer size greater than zero; it doesn't care how long the input is; and it works correctly for the final read whatever its size.
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

Again you haven't counted this as part of the fixed-length transfer size.
But I must say you would be better off using chunked transfer mode and letting HttpURLConnection do all the heavy lifting: all you need then is the copy loop above.
Comment: @Stallman It doesn't make any difference to the code how large the file is. I've already stated that. I don't know why you're asking.
Comment: Thank you very much EJP, I have fixed all, and today I'll test with an old device and see if I still receiving the out of memory error :-) I'll say you the results, thanks!!
Comment: when I do this and I upload a text file --*****
Content-Disposition: f... is added to the start of the file and --*****-- to the end
Comment: @EJP  What if the file is very large?
Comment: @EJP  or David. Could you please update the complete correct code? I follow an example which is almost the same as yours on the net. And that tutorial makes several mistakes as EJP describes. Could you update your answer? If it solves my problem, I would ask a new question, and you can get the reputation.
Comment: @EJP  Following your statement, I only have to create a `FileInputStream` called `in`, and the argument is the target file,
and new `DataOutputStream(conn.getOutputstream);` which is called `out`. Regarding to the header setting, use `chuncked transfer mode`: conn.setChunkedStreamingMode(1024);, and finally adopt the `while loop`. Is that all?
Comment: The argument of `new FileInputStream` is the *source* file.
Comment: Well, it can't work. Maybe the server doesn't support `setChunkedStreamingMode`, according to the official document:
http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode(int)
It indicates that some server may not support it. But I think it's the problem of `setChunkedStreamingMode(THE NUMBER)` What does it actually mean? In android development official doc, http://developer.android.com/reference/java/net/HttpURLConnection.html, if we don't know the body size, it sets the number to `0`
Comment: Define "doesn't work", and "server". I've never used one that didn't support chunked transfer mode. Your link doesn't say a word about it either. You need to post actual symptoms here, not guesswork.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/63403/discussion-between-stallman-and-ejp).
Comment: Just try it this way and report the results. `THE_NUMBER` is the size of the chunks. Setting it to zero uses a default, typically 1024. You don't have to know the body size in advance. All this is already stated in your link.
Comment: Well, I got the error message in debug mode. I catch the exception: `sendto failed: EPIPE (Broken pipe)`. Whenever I use `setChunkedStreamingMode`, the error msg appears.
Comment: OK so that means the server is closing the connection while you're still sending. There could be several reasons for that other than chunked transfer mode: for example, you may be exceeding an upload size limit. What is the server?
Comment: `uhttpd`. But as I know there is no size limit for the server configuration.
Comment: I use `setFixedLengthStreamingMode(FileSize + boundaryString);` to solve the problem. `FilSize` is the size of file(bytes) and bourdaryString is the size of string segment which looks like: `boudnaryXXXXX--`. But I still can't figure out why `setChunkedStreamingMode` can't work.
Comment: @Stallman It *can* work, and it *does* work. But if you set it, you don't have to define the chunks yourself: just write the data. Chunking will happen automatically.