Can sub-optimality of various hierarchical clustering methods be assessed or ranked?

Question: Classic agglomerative hierarchical clustering methods are based on a greedy algorithm. This means that they (many of them) are prone to give sub-optimal solutions instead of the global optimum result, especially on later steps of agglomeration. To clarify: each of the agglomerative methods makes the best choice of which two clusters to merge on a given step $q$, the choice that minimizes (to value $\delta_q$) the coefficient of colligation $\delta$ on the step; however, it is not impossible that if the algo had chosen not the best but a bit worse choice on some previous step(s) it then would have been able to minimize the coefficient on step $q$ to value less than that $\delta_q$ while preserving monotonical growth of $\delta$. Globally optimal solution on step $q$ corresponds to the absolutely minimal such way achievable value $\delta_q$ with the restriction remaining that $\delta_q \ge \delta_{q-1} \ge \delta_{q-2} \cdots$.
Risk of sub-optimality is the main reason why hierarchical clustering is commonly not recommended with large amount of objects (say, more than several hundreds): the researcher typically wants few clusters and therefore looks at later steps, but if a later step is, say, a 1000th one, it is more suspicious for having gone astray from globally optimal partition possible on the 1000th step than, say, a 100th step gone from globally optimal partition possible on the 100th step. This looks a matter of dictum.
My question is what do you think about which among well-known agglomerative methods - single linkage, complete linkage, average linkage (within groups), average linkage (between groups), centroid, median, Ward's sum-of-squares - I'm mentioning those in SPSS, but there are other similar variants as well - are more and which are less prone to the sub-optimality flaw as the step number grows. Intuition suggests to me that single or complete linkage aren't prone at all and always give their globally best solutions, because these methods don't engage in computation of any statistics derivative from raw distances (e.g. centroids). I may be right as well as not. What are about the rest methods? Can someone here attempt to analyze the (relative) degree of local-optimum risk of the above concrete greedy algorithms?
Illustration. Fortunately, for Ward method we have clues to observe how sub-optimality accumulates as $q$ grows. Because there is a well-known iterative method that attempts to optimize the same function $\delta$ as Ward does; this is K-means clustering: both try to minimize pooled within-cluster sum-of-squares $^1$. We can do Ward clustering and on each step save cluster centres, and use those as initial centres in K-means procedure. Will K-means improve the Ward's solutions in terms of sum-of-squares?
[$^1$ Footnote: Ward minimizes the increase in sum-of-squares on its steps. Another hierarchical method, variance method MNVAR (see Podany, J., 1989, for various hierarchical methods), which is less well-known, minimizes mean-of-squares within clusters. Both these methods can be considered as a kin to K-Means, with Ward's being somewhat better minimizer of final SSwithin than MNVAR (my own simulation studies).]
Note. This illustration tests Ward's observed $\delta_q$ values not against its own global optimum values which we can't know because we are unable to try, for each step, all innumerable alternative reconstructions of earlier steps in order to find out the minimal possible $\delta_q$; it tests against K-means optimality (which is almost its global here because initial centres provided by Ward can be regarded reasonably good start for iterations).
Here is some data (5 not well separated clusters, 183 points). The data underwent both Ward clustering session and K-means clustering sessions, as described.

Results (value of $\delta$) for clusters 50 through 2 are shown below. Although the 2 curves are close to each other, K-means' values are somewhat better. That is, K-means is more optimal than Ward.

The last picture plots $\delta^{Ward}/\delta^{Kmeans}$. The trend is clearly seen: as the number of clusters diminishes (that is, step $q$ for Ward grows), Ward tends to become less optimal relative to K-means.

One tempting question would be whether the relative sub-optimality of Ward (the value of $\delta^{Ward}/\delta^{Kmeans}$) on these latest 49 steps of agglomeration would be higher if I analyzed in the same fashion 1830 data points instead of just 183.
Comment: Try non-spherical clusters, too. Or you might "overfit" your analysis to gaussian clusters.
Answer: Only single-linkage is optimal. Complete-linkage fails, so your intuition was wrong there. ;-)
As a simple example, consider the one-dimensional data set 1,2,3,4,5,6.
The (unique) optimum solution for complete linkage with two clusters is (1,2,3) and (4,5,6) (complete linkage height 2). The (unique) optimum solution with three clusters is (1,2), (3,4), (5,6), at linkage height 1.
There exists no agglomerative hierarchy that contains both, obviously, because these partitions do not nest. Hence, no hierarchical clustering contains all optimal solutions for complete linkage. I would even expect complete linkage to exhibit among the worst gap between the optimum solution and the agglomerative solution at high levels, based on that example... An this example likely is a counter example for most other schemes (except single linkage, where this data set degenerates).
You may be interested in studying this article:

Gunnar E. Carlsson, Facundo Mémoli:
  Characterization, Stability and Convergence of Hierarchical Clustering Methods. Journal of Machine Learning Research 11: 1425-1470 (2010)

and the references contained therein, in particular also:

Kleinberg, Jon M. "An impossibility theorem for clustering." Advances in neural information processing systems. 2003.

These seem to indicate that given some mild stability requirements (which can be interpreted as uncertainty of our distance measurements), only single-linkage clustering remains. Which, unfortunately, is all but usable in most cases... so IMHO for practical purposes the authors overshoot a bit, neglecting usefulness of the result over pretty theory.
Comment: Ah, yes. That's quite clear. Thank you, Erich, for answering this old question. I upvoted all the answers to it.
Answer: A partial answer to your question follows. Single linkage clustering is equivalent to the computation of a minimal spanning tree (references are easy to find). If we disregard ties the result is garantueed to be an optimal solution, or one among a set of optimal solutions, in that the total branch length will be minimal. I think the naive construction process also garantuees the property that you ask for (when cutting a dendrogram). As for complete link clustering, I do not know, and I think it is a good question. A famous reference in this field is the book by Jardine and Simpson, mathematical taxonomy. They conclude that single linkage clustering, for all its shortcomings, is mathematically and conceptually the stand-out method and consider it the most appealing. I don't agree with that, but the book is a very good read. Perhaps their results might imply that the property you seek does not hold for complete link clustering, but this is speculation.
Comment: Thank you, I liked your response although it adds little to what I'm aware myself, in particularly regarding single linkage method; I've thought, it must be always fully optimal. Other methods intrigue me more. Thank you for regarding my question as good one. I've added something to it recently.
Comment: I think it is possible to construct an example with 6 points, where complete link clustering will give two clusters, with the largest pairwise distance among those two clusters a certain value delta. In that example, another partition into two clusters yields a smaller largest pairwise distance. It seems to me this will answer your question - is that correct? I don't have the book anymore, but this is exactly the kind of phenomenon that Jardine and Simpson study.


MySQL query is not returning correctly

Question: --Edit
I still dont get it for some reason. I will give more detail about my problem.
jobs table
   id, title ... all details
    1, title1,...
    2, title2,...
    3, title3,...
    4, title4,...

job_user table
id,id_job,id_user
1,1,1
2,2,3
3,3,3
4,4,4

following_job table
id,id_job,id_user
1, 1, 3

So basically, user 3 has 2 jobs (2,3), and he follows job 1 of user 1. so, if i login as user 3, i would like to get all details jobs of user <> 3 (just the requirement that i need to do).
i would get the result
id,id_job,id_user
    1,1,1
    4,4,4

My goal results would be :
id,title..., following_id
        1,title1,...,1
        4,title4,...,0

the following_id will be added as result above, since user 3 followed id_job 1 so its following_id = 1 else = 0. And id_job 1,4 will joined with jobs table to get details about it : title ...
I am doing the follow/unfollow job functionality
Thanks all
Comment: Do you have a table which contains the job IDs for which you want to search?
Comment: Why is it id 2 for id_job 3 in your results? The table associates id 1 with it.
Comment: what do you want in the first column ? row number or what ?
Comment: Your id column in your result is nonsensical. That aside, consider handling the logic of missing values in application code (e.g. PHP), if that's available.
Comment: Thank you guys for quick answer. i edited my question including my full query
Answer: Typically you would have a second table which contains the id_job values you want to search/match, something like this:
has_jobs

id_job | (other columns...)
2
3

Then, you could just left join has_jobs to following_job to get the result you want:
SELECT t2.id
       t1.id_job,
       CASE WHEN t2.id_job IS NULL THEN 0 ELSE 1 END AS following_id
FROM has_jobs t1
LEFT JOIN following_job t2
    ON t1.id_job = t2.id_job

If you don't have an actual has_jobs table, then you could use an inline table instead:
SELECT t2.id
       t1.id_job,
       CASE WHEN t2.id_job IS NULL THEN 0 ELSE 1 END AS following_id
FROM
(
    SELECT 2 AS id_job
    UNION ALL
    SELECT 3
    -- add more IDs here if wanted
) t1
LEFT JOIN following_job t2
    ON t1.id_job = t2.id_job

Comment: Biegeleisn : Thanks for your answer. I have been trying but no luck. Can you please take a look my post that i edit. Thanks much

MySQL query is not returning correctly


Combine data from previous week with current week in R

Question: Hi I have a dataframe given below
s.no week number   Income
1     6            52
2     7            74
3     8            13
4     9            60

I need this dataframe to be changed with an addition of a new column Total_income having the formula -
 100% value of Income in current week +
  60% value of income in previous week +
  30% value of income in previous to previous week

Output should be like -
s.no week number Income Total_Income
 1      6          52      52
 2      7          74      74+0.6(52)=105.2
 3      8          13      13+0.6(74)+0.3(52) = 73
 4      9          60      60+0.6(13)+0.3(74) = 90

Kindly help
Comment: is the data always ordered by week number, ie. the values in week number column will always be sorted?
Answer: Assuming that the dataframe data is ordered by week number. If not, begin with data %>% arrange(week_number) %>% (note column renamed to remove space).
library(dplyr)
data %>%
  mutate(Total_Income = Income + 0.6 * lag(Income, default = 0) +
         0.3 * lag(Income, n = 2, default = 0))

Answer: The base R option with sapply. For every value in week_number we find the Income for that week, along with previous two weeks and sum them together with necessary arithmetic.
with(df, sapply(week_number, function(x) { sum(Income[week_number == x],
  0.6 * Income[week_number == x-1], 0.3 *Income[week_number == x-2])
}))

#[1]  52.0 105.2  73.0  90.0

Answer: We can use data.table and do this in a single line
library(data.table)
setDT(d)[,Total_Income := Reduce(`+`, Map(`*`,shift(Income,n=0:2,fill=0), c(1, 0.6, 0.3)))]
d
#   s.no weeknumber Income Total_Income
#1:    1          6     52         52.0
#2:    2          7     74        105.2
#3:    3          8     13         73.0
#4:    4          9     60         90.0

Or we can do a cross product
c(crossprod(do.call(rbind, shift(d$Income, n = 0:2, fill = 0)), c(1, 0.6, 0.3)))
#[1]  52.0 105.2  73.0  90.0


The $f^{-1}(y)$ is locally constant where $ y$ ranges through regular values

Question: Let $f: M \longrightarrow N$ be a smooth map between two manifolds of the same dimension, with M compact, and a regular value $y \in N$. Then the number of points in $f^{-1}(y)$ is locally constant as a function of $y$, where $y$ ranges through regular values.
I read the proof in Milnor's book "Topology from the differentiable viewpoint" but if I'm not wrong this proof concerns regular values with preimage. But I don't know how to prove it in the case where $y$ is not the preimage of some $x \in M$. In this case $f^{-1}(y)$ should be locally $0$ in a neighborhood of $y$, right?
Comment: So locally constant...
Comment: right! but how could I prove it for this special case?
Comment: The preimage of a point is closed.
Comment: Possible duplicate of [A doubt from Milnor's "Topology from a Differentiable Viewpoint".](https://math.stackexchange.com/questions/936272/a-doubt-from-milnors-topology-from-a-differentiable-viewpoint)
Answer: Notice that the source $M$ is compact, so the image is closed. Therefore, the complement of the image in $N$ is open.


Development of an application on common SDK for Android, Blackberry and Symbian

Question: I need to develop an application on Android, Blackberry and Symbian in Java environment. For that I need to use only one common SDK for all OS. Is it possible, and how? Please tell me the software that is suitable for developing the application.
Answer: That is a big question and this is a market that is quickly changing. There are a number of technologies that are trying to provide the "write once, run anywhere" development experience for smart phones. I don't know that you will find an answer in Java, but there may be a tool or framework that can help you.
Here is a short list of some of the ones I remember:

PhoneGap
Appcelerator Titanium
Rhomobile
Sencha Touch

Also, see some older Stack Overflow posts, like:

Comparison between Corona, Phonegap, Titanium
Developing cross platform mobile application
Alternative ways for developing for Android
Alternatives For iOS Development Under Windows

Updates:

Metismo
MoSync
Comment: Hi Michael thanks for immediate response..the SDK that u mention are not supporting all the OS. and do u know about the Kony plug-in which suports for ALL the three OS.Is it open sorce. i did nt find any plug-in downloda for that.can u plz help me to find that. thanks in advance
Answer: As far as I know, you cannot develop the UI portions in Java using any of the cross-platform tools (at least for these platforms). For the non-UI portions, I think that BlackBerry is the most restrictive, since it is basically Java 1.3 (no generics). If you target this lowest common denominator, you can write the non-UI portions as a library shared among all the platform-specific products.
Answer: With only one SDK i don't think it's possible.
You can develop a Web App that all can view probably.. but i see no other way.
Comment: what is web apps that we can use


Como retornar um valor ao invés de uma [object Promise]

Question: Eu tenho esse código e quero retornar a string não a promise, mas não sei como exatamente como fazer, já tentei olhar outras soluções no site porém não consegui aplicá-las no meu código. (estou usando o axios)
async function traduzCategoria(texto)
{
    if (typeof texto === "undefined"){
        return "sem categoria";
    }

    let textoUrl = texto[0].replace(/ /gi, "+");
    textoUrl = texto[0].replace(/&/gi, "and");

    let urlYandex = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + keyYandex
        + "&text=" + textoUrl + "&lang=pt";

    let res = await axios.get(urlYandex)
                .then(function (response) {

                    let textoTraduzido = response.data.text[0];
                    return textoTraduzido;

                })
                .catch(function (erro) {
                    return "erro na categoria";
                })

    return res;
}

A função não espera a promise para retornar o valor.
Answer: Você está usando a sintaxe do async/await de maneira incorreta. O correto seria:
try {
    const response = await axios.get(urlYandex);

    return response.data.text[0];
} catch(error) {
    return error;
}

Caso for usar o then/catch da Promise retornada pelo axios, remova a sintaxe do async/await, que foi feita exatamente para tornar o código menos verboso.
Fico à disposição, até mais.
Comment: Não diria que usar o `await` como ele fez está "errado"... Afinal, o `then` está retornando outra `Promise`.


Why isn't my custom region showing up?

Question: I'm trying to create a new region called 'usermenu' for my theme in Zen. I've therefore added
region[usermenu] = User menu

to the mytheme.info file, added
<?php if ($logged_in): ?>

      <?php print render($page['usermenu']); ?>

<?php endif; ?>

to the mytheme.tpl.php file and added
#usermenu {
  background-color: #fff;
  height: 35px;
}

to one of my CSS files. After clearing caches multiple times, the new region is displayed correctly and I can detect it with Firebug, but it doesn't show up in the block section.
What's going wrong and how can I solve this?
Comment: Make sure you're looking at the correct "Theme" tab in the blocks admin page.
Comment: @DavidThomas: Yes, I'm looking at the correct tab. When I hit "Demonstrate block regions (mytheme)", the 'usermenu' region isn't highlighted.
Answer: I found it! It was just a stupid typo in the .info file. I should have inserted regions[usermenu] = User menu...

Why isn't my custom region showing up?


Stop reusing PHP_VALUE for different sites with PHP-FPM

Question: I noticed the following behavior or PHP-FPM:
Take a look at these two Nginx configs:
server {
    listen         80;
    server_name    example.com;
    location / {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME  /srv/www/i.php;
        fastcgi_param PHP_VALUE "display_errors=1";
        include fastcgi_params;
    }
}
server {
    listen         80;
    server_name    example.net;
    location / {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME  /srv/www/i.php;
        include fastcgi_params;
    }
}

and /srv/www/i.php file:
<?php phpinfo();

As you can see the only difference is fastcgi_param PHP_VALUE "display_errors=1";.
Now if you kill all FPM workers, and open example.net first, you will see display_errors is Off as expected. And at example.com you will see display_errors is On.
But if you visit example.net again and this request is proceeded by the same worker, you will get display_errors as On.
All FPM workers are working in the same pool.
Question: how to make example.net always work with default settings?
Possible solutions:

Define PHP_VALUE with the desired settings in example.net config as well.
Seems to be a "right" solution - create separate pools of workers for each site.

But we have a lot of websites on our server, and both solutions mean a lot of routine work to set up. I was wondering if there is an easier way.
Update:
display_errors setting in my example was chosen just to demonstrate the problem. The same situation takes place with any php.ini setting. As per comments, it is a bad idea to mix production and development sites on a single server.
Comment: Side note: As of PHP 5.2.4 [display_error](http://php.net/manual/de/errorfunc.configuration.php#ini.display-errors) expects a string value and should be set to either `stdout` (default) or `stderr`.
Comment: Another option is to put your non-production sites on an entirely different server.
Comment: @Daniel I will keep it in mind, thanks) This directive was chosen for example. In the real life I faced this problem when I set `error_log=/some/file.txt` for the only site and noticed that there were errors of other sites there as well
Answer: The reason this happens is most likely that "PHP settings passed with php_value or php_flag will overwrite their previous value", as described PHP-FPM documentation.
I assume that in your PHP configuration display_errors is disabled. Then you visit the .net-page, in which your phpinfo() confirms that it is disabled.
Then you visit the .com-page and Nginx passes display_errors=1 to your PHP-FPM worker in that same pool. That overwrites the previous value of 0 with the new value 1. You can confirm that with phpinfo().
Now the PHP-FPM pool settings is set to display_errors=1.
When you visit the .net-page again, phpinfo() indeed confirms that display_errors=1 because it was overwritten when Nginx passed the value of 1 to the same pool that now handles another of your websites.
The solution is either to move development to another server, as suggested in the comments. Or to create a dedicated PHP-FPM pool for your site, which is the least you should do.
Bonus:
And please don't do this in your Nginx configuration: fastcgi_param PHP_VALUE "display_errors=1";
That ought to be in the php configuration file, preferably in the site's own fpm pool configuration.

But we have a lot of websites on our server, and both solutions mean a lot of routine work to set up. I was wondering if there is an easier way.

You can use the per pool prefix for a quick fix. In any case, putting multiple sites on a single worker pool is a bad idea because I only need to get one of your sites to execute a malicious php script of mine to compromise ALL other sites that use the same worker, without any effort.
Comment: Thanks! It looks like I have to revise my approach of using PHP-FPM


Differential Equation-Separation of variables

Question: 1) Solve the following differential equation by separation of variables (or otherwise) $$\frac{dy}{dx}-1=e^{x-y}$$.
What I tried:-
Suppose $$z^2=e^{x-y}$$
        $$\Rightarrow 2z\frac{dz}{dx}=e^{x-y}(1-\frac{dy}{dx})$$
$$\Rightarrow 2z\frac{dz}{dx}=z^2(1-\frac{dy}{dx})$$
$$\Rightarrow 2\frac{dz}{dx}=z(1-\frac{dy}{dx})$$
$$\Rightarrow \frac{dy}{dx}=1-\frac{2dz}{zdx} \tag1$$
Again, $$\frac{dy}{dx}-1=e^{x-y}$$
$$\Rightarrow \frac{dy}{dx}=1+z^2 \tag2$$
Equating $(1)$ and $(2)$,
$$1+z^2=1-\frac{2dz}{zdx}$$
$$\Rightarrow z^3dx=-2dz$$
$$\Rightarrow z^{-3}dz=-\frac{1}{2}dx$$
$$\Rightarrow \int z^{-3}dz=\int -\frac{1}{2}dx$$
$$\Rightarrow \frac{z^{-2}}{-2}=-\frac{1}{2} x+\frac{c}{2}$$
$$\Rightarrow -z^{-2}=-x+c$$
$$\Rightarrow z^{-2}-x+c=0$$
Am I correct ?
Comment: @Moo I was doing same thing moo
Comment: **Hint:** Try letting $$v = y - x \implies v' = y' - x'$$ Substitute those and then you get a Separable Equation.
Comment: With everyone telling you other ways of solving the problem, it may not be clear: the answer to your actual question is "yes". What you did is correct. It may not be the simplest approach possible, but there is nothing wrong with it (other than not translating back into $x$ and $y$ instead of the variable $z$ that you introduced).
Comment: @KingTut - no, I didn't downvote. You didn't answer the exact question asked, but you and the others satisfied the actual need. I just thought it would be good to point out that the work in the question was actually correct.
Comment: @PaulSinclair Thats why i said you are right and you did good work! :)
Comment: @paul did you downvote everyone? Actually you are right that noone checked his work.
Answer: Lets try $x-y = t$ and $t_x = 1-y_x$
$$-\frac{dt}{dx} = e^t \\
\int -e^{-t} dt = \int dx\\
e^{-t} = x+c$$
Answer: If you put $z=x-y$ then you can find easily the solution of the problem.
By putting $z=x-y$ the above ODE becomes $$-\frac{dz}{dx}=e^z.$$
By separation of variable, $$-e^{-z}dz=dx.$$
By integrating we get $$e^{y-x}=x+c.$$
Answer: $$y'-1=e^{x-y} \implies (y'-1)e^{y-x}=1 $$
Integrate simply since on the left side you have a derivative
$$\int e^{y-x}(y'-1)dx=x+K \implies \int (e^{y-x})'dx=x+K$$
$$e^{y-x}=x+K$$
Another way
substitute $y=\ln(z)$:
$$\frac{dy}{dx}-1=e^{x-y}$$
$$\frac{z'}{z}-1=\frac {e^{x}}z$$
$${z'}-z= {e^{x}}$$
$$({ze^{-x}})'=1$$
$$z=e^{x}(x+K)$$
$$e^y=e^{x}(x+K)$$
$$\boxed{y=x+\ln|x+K|}$$
Comment: Quite a nice observation!
Comment: Thank you @KingTut.....


perfect Lie algebra but not semisimple

Question: Lie algebra $\mathfrak{g}$ is perfect if and only if $\mathfrak{g}=[\mathfrak{g},\mathfrak{g}]$.
And we know semisimple Lie algebra must satisfy the $\mathfrak{g}=[\mathfrak{g},\mathfrak{g}]$ then it's perfect.
What is the example of perfect Lie algebra but not semisimple? And what's the sufficient and necessary condition for a perfect Lie algebra to be semisimple Lie algebra?
Comment: See [this MO-question](https://mathoverflow.net/questions/60498/lie-algebra-semisimple), and also [this MSE-question](https://math.stackexchange.com/questions/2028737/which-vector-spaces-have-a-perfect-lie-algebra-structure).
Answer: I think the set of $4$-by-$4$ matrices of the form
$$\pmatrix{*&*&*&*\\*&*&*&*\\0&0&*&*\\0&0&*&*}$$
will be an example.
Comment: you need to prescribe both diagonal blocks to have trace zero.
Answer: Take any semisimple Lie algebra $L$ of dimension $n$ and an irreducible representation $V$ of $L$, of dimension $m \ge 2$ and define a bracket on $L \times V$ by
$$ [(X,v),(Y,u)] := ([X,Y],Xu-Yv). $$
This turns $L \times V$ into a perfect Lie algebra with $\text{Rad}(L \times V) = V$. The dimension is $n+m$. It is not semisimple.
A necessary and sufficient condition for a perfect Lie algebra to be semisimple is that its solvable radical is trivial.

perfect Lie algebra but not semisimple


laravel how to add a property to the authenticated user

Question: The authentication table is the admin table. One of its column is the picture column. This is column just to save the location of the image, so it is varchar type.
I have a master layout for all the pages, and I want to add the admin's image in that master layout.
I did this in a controller
$user = Auth::user();
        $image_user_path= $user->picture;
        $image_user_extension = pathinfo($image_user_path, PATHINFO_EXTENSION);
        $image_user_data = file_get_contents($image_user_path);
        $user->base64 = 'data:image/' . $image_user_extension. ';base64,' .base64_encode($image_user_data);

Please check that the $user now has a base64 property
I did this in a view
base64}}"/>

That works perfectly
However, the property is that I have to add the code in each controller, is there anyway so I can add it in one place and that is it?
at the top of my mind, I can think of the BaseController maybe there ?
Comment: oh, you are so beautiful!!!
Answer: Make a method on the User model and then call the function in your views, e.g.
public function imageUrl() {
    $image_user_path = $this->picture;
    $image_user_extension = pathinfo($image_user_path, PATHINFO_EXTENSION);
    $image_user_data = file_get_contents($image_user_path);
    return 'data:image/' . $image_user_extension. ';base64,' .base64_encode($image_user_data);
}

Then, in your view:
imageUrl() }}">

Comment: Brilliant, fascinating, amazing, excellent, It works. many thanks


BlazeDS: Converting action script type Class (for an embded image) to Java

Question: I am using BlazeDS for my flex3 application and I need to transfer an embedded image from actionscript to java. Any hint on how to do that? To what java class does actionScript's Class type correspond?
Thanks
Answer: In one of my projects I have done this by serializing the image (PNG) to a byte array and transferring the array, and then reconstruct it.


Why was spitball allowed to some players?

Question: Wikipedia has this to say on the history of banning spitball:

The spitball was banned in two stages. In the winter of 1919–1920, managers voted to partially ban the spitball, allowing each team to designate at most two pitchers who would be permitted to legally throw spitballs. Then, following the 1920 season, the spitball was banned leaguewide, except for existing spitballers who were grandfathered in and allowed to keep throwing the pitch legally until they retired.

The first stage looks highly surprising, but somewhat fair.  It's a way to allow some spitballs in the game but not all spitballs.
The second stage puzzles me.  Did this decision lead to inequality of rules between players and teams?  Was such inequality real, and seen as a problem?  Were there any considerations that made banning spitball for everybody impractical?
Comment: Without reference available, it's because the spitball was the best-by-far (or even only) technique that made these pitchers worthwhile. Changing that rule creates huge headaches for team management who are now forced to either buy out a contract or pay someone to take up space they can't use.
Answer: It wasn't allowed for some players.  It was a rule that used a cut off date.  If you were pre-1920 and threw spitballs before, you can throw them after.
If not, no more spitballs.  Meaning the last time a spitball was legally thrown was probably around 1935 given there was a younger spitballer in 1919.  Since then it has been banned.
That doesn't mean it wasn't thrown, it just means it wasn't thrown legally.  There have been a number of players that have made their careers on spitballs.  One of their key traits was the ability to throw it and not get caught.
There are rules all over sports exactly like this.  For instance in baseball and hockey the playing with a helmet was not forced outright to vets who had played without.
As far as the spitball usefulness this is directly related to the spin rate of the ball.  With a substance that makes a ball slippery a player can achieve a much better spin rate.  This will account for any type of curve/breaking ball having a more drastic turn (whatever way it will turn).
Comment: Do you want to incorporate also the comment from @Nij?  I believe that your answer and his comment may click together very well, but I'm not exactly sure whether you guys are actually in agreement regarding the why.


How does Pi fit on the real number line?

Question: Since the decimal expansion of Pi is infinite and unpredictable, the number just to its left and just to its right would have to conform to Pi's ever changing value if we are to suppose there are no gaps between successive numbers.
If that is so, then the two numbers flanking Pi, must also be flanked by such numbers that do not allow gaps. Logically, this process must continue for all numbers to the left and to the right of Pi.
If this is the case, then no other kind of number could ever lie to the left or right of Pi without creating a gap. How does Pi 'fit' on the number line?
Comment: The digits of $\pi$ are perfectly predictable, in the sense that we have very simple algorithms that can compute as many of them as we want. There are numbers with much less predictable digits than this, such as Chaitin's constant, where no such algorithm exists.
Comment: Well couldn't you apply this argument to any number?
Comment: The number "right next to" another number is irrational, because it would keep going on forever. For example, the number "right next to" 1 is irrational. It would be 1.0000000000000000000000000000..., and it can never end in a 1-digit, because there would always be another power of ten to add another digit 0.
Comment: In other words, the real number-line continuous, not discrete. But natural numbers, integers, or whole numbers, for example, are. For example, there is a NATURAL NUMBER "right next to" 3, 4 or 2.
Comment: It's also very important to note that $\pi$'s value is not "ever-changing", it has one specific value that stays the same, it just can't be expressed exactly as a rational number.
Comment: There is no "next" or "previous" number in the reals , neither a rational one nor an irrational one. Between two real numbers , there are always infinite many other real numbers , no matter how close they are.
Answer: The problem is that you could apply this type of reasoning to any number. On the real number line, it is impossible to define exactly which number is after another, as you have shown. We could get closer and closer rational approximations of $\pi$, but never $\pi$ exactly. The answer to your question is that numbers don't really 'fit' on the real number line as it is hard to even say what numbers like $\sqrt 2, e,\pi$ etc. really are, much less define the numbers that are perfectly adjacent to them.
Sidenote: as a result, the set of all real numbers is "uncountable".


How to save WorkItemsAffected to a Risk

Question: How do I save or link a feature item to an existing risk? I was trying to post but it did not work:
<code>    var url = "https://rally1.rallydev.com/slm/webservice/v2.x/risk/" + riskRecord.data.ObjectID + "/workitemsaffected";
    return Q.Promise(function (resolve, reject) {
        $.ajax({
            url: url,
            method: 'POST',
            dataType: 'json',
            data:"/portfolioitem/feature/" + portfolioItemObjectID,
            headers: {
                'Content-Type': 'application/json'
            },
            xhrFields: {
                withCredentials: true
            },
            success: function (item) {
                resolve(item.QueryResult.Results);
            },
            error: function (e) {
                console.error(e);
                resolve(false);
            }
        });
    });
</code>
Thank you!!
Answer: Actually, setting the ref of WorkItemsAffected saves the WorkItemsAffected to Risk.
<code>riskRecord.set('WorkItemsAffected', [{
                _ref: "/portfolioitem/feature/" + valueRecord.data.PortfolioItemObjectID
            }]);
</code>
Thanks!

How to save WorkItemsAffected to a Risk


Replace hr element with correct letters for Hangman game - javascript

Question: After generating the number of dashes according to the length of the word, how would I go about replacing these dashes with the correct letter the user inputs. In most examples, I have seen people using arrays for this purpose. But since my dashes are hr elements, how should I be doing this?
The following is my javascript code:
var words = ['quaffle', 'bludger', 'pensieve', 'harry', 'lupin',
    'butterbeer', 'polyjuice', 'patronus', 'horcrux', 'voldemort'
];
correctletters = '';
missedletters = '';

function getRandomWord() {
    randomWord = words[Math.floor(Math.random() * words.length)];
    wordlength = randomWord.length;
}

function drawDashes() {
    for (var i = 0; i < wordlength; i++) {
        var dash = document.createElement("HR")
        document.body.appendChild(dash);
    }
}

function getGuess() {
    letterGuessed = document.getElementById("inputfield").value.toLowerCase();
    document.getElementById("inputfield").value = null;
    alert(randomWord);
    alert(letterGuessed);
    r = randomWord.includes(letterGuessed);

    if (r == true) {
        correctletters = correctletters + letterGuessed;
        alert("correct letters: " + correctletters);
    } else {
        missedletters = missedletters + letterGuessed;
        alert("missed letters: " + missedletters);
    }

    guess = missedletters + correctletters;
    displayGuessedLetters();
}

function displayGuessedLetters() {
    guessedletters = document.createElement("div");
    content = document.createTextNode(guess);
    guessedletters.appendChild(content);
    container = document.getElementById("inputcontainer");
    container.appendChild(guessedletters);
    guessedletters.style.cssText = 'font-family: "Josefin Sans"; font-size:
    30 px;
    text - transform: uppercase;
    color: rgb(255, 85, 49);
    ';
}

function replaceDashes() {
    /*Code to replace dashes here.*/
}

Answer: You can do this as:
function replaceDashes()
{
   var list = document.getElementsByTagName("hr")[0];
   list.parentNode.removeChild(list);
}

Comment: Thanks, will try. If I wanted to change the third hr to the letter "A". How would I do that?
Comment: https://stackoverflow.com/questions/7093417/using-jquery-to-replace-one-tag-with-another


drupal_add_js in html template file

Question: I am using a zen subtheme and I am trying to add some javascript using the drupal_add_js
 on a certain node.
When I use the drupal_add_js from within the html--node--XX.tpl.php file, it does not work.
But when I use it in the page--node--XX.tpl.php it does. I don't understand what causes the difference in the behavior. I thought that this would be the same.
These are the lines I am adding in both cases:
drupal_add_css("sites/all/libraries/shadowbox/shadowbox.css", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("sites/all/libraries/shadowbox/shadowbox.js", array('type' => 'file', 'scope' => 'header', 'weight' => 5));
drupal_add_js("Shadowbox.init({skipSetup: true});", array('type' => 'inline', 'scope' => 'header', 'weight' => 6));

Can anyone illuminate me here?
Answer: You can try to insert the JS files by the preprocess function in your theme's template.php file:
Here goes an example:
function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

You can use an if() to validate the current path in the $variables in order to prevent the script to be loaded on every page.
To debug the $variables values you can install the devel module an use the dpm() function.
For example:
function MYTHEME_preprocess_page(&$variables) {
  dpm($variables);
}

Comment: You can use the `current_path()` function to validate the url to load the script. Like:
`if(current_path() == 'node/X')
  drupal_add_js(drupal_get_path('theme', 'MYTHEME');`
Comment: I suppose you mean `drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');`  Yes, this is good! Thanks.
Comment: I have tried successfully the preprocess solution for the whole site.  It was in the 'if' part that I got confused. Did not know which variable to check. Still unsure. Normally, in a template I would find the nid from a url argument. Does this work in the template.php file? Thanks anyway.
Comment: Exact. Sorry about that. When I realized that I could no longer edit the comment to fix this error.
Answer: Using drupal_add_js in a variant of the html template will never work, because the styles are printed in the html template. At the time you call drupal_add_js the variable containing the styles have already been created and you are too late to alter it with drupal_add_js.
The reason it works in page templates is that it is parsed before the html template so the variable containing the styles that is printed in the html template has not yet been generated.
Comment: Ah! This makes sense. This means that I can use it to page--node--xx.tpl.php or node--xx.tpl.php etc but never on a html.tpl.php variant, right?
Comment: @nikan True. You could do it in a `html.tpl.php` but it would require that you rebuild the `$scripts` variable and did it before it was printed. In other words a lot more complicated.
Answer: Structure is
html.tpl.php
->page.tpl.php
-->node.tpl.php
So it is like html--page--node(--XX).tpl.php
Simply use node--XX.tpl.php but make sure there is a html.tpl.php, page.tpl.php and node.tpl.php file in your subthemes directory.
Comment: I am confused: you are suggesting that I use three files? I tried using the html--page--node(--XX).tpl.php but it returns a blank page.
Comment: Simply use node--XX.tpl.php and ignore the structure
Answer: If you are looking to add javascript to individual nodes the best option is Code Per Node
Comment: Useful. Thanks. But in this case I would rather do it through the core drupal functions in the template, than through a module.

drupal_add_js in html template file


Prove that $\forall P$, $Q \in \mathbb{B}.$ $(P \Rightarrow Q) \Leftrightarrow(\neg P \vee Q)$ without using truth table

Question:
Prove that $\forall P$, $Q \in \mathbb{B}.$ $(P \Rightarrow Q) \Leftrightarrow(\neg P \vee Q)$ without using truth table

The grader says that my proof below is wrong: "To prove an iff statement, you should prove from two directions instead of cases. In this question, you need to prove $(P \Rightarrow Q) \Rightarrow (\neg P \vee Q)$ AND $(\neg P \vee Q) \Rightarrow (P \Rightarrow Q).$" I don't think that the grader is right about my approach. Is my proof correct or wrong?
To prove that $(P \Rightarrow Q)$ and $(\neg P \vee Q)$ are equivalent, we first consider the ways for the equivalence to fail; there are two such cases:
Case 1. Suppose that $(P \Rightarrow Q)$ is true and $(\neg P \vee Q)$ is false.
In this case, since $(\neg P \vee Q)$ is false, $Q$ and $\neg P$ must all be false, which means that $P$ is true. So, $P$ is true and $Q$ is false, which means that $(P \Rightarrow Q)$ is false, which contradicts our statement. So Case 1 is impossible.
Case 2. Suppose that $(P \Rightarrow Q)$ is false and $(\neg P \vee Q)$ is true.
In this case, since $(P \Rightarrow Q)$ is false, we know that $P$ is true and $Q$ is false. So, $\neg P$ is false. Since both $\neg P$ and $Q$ are false, $(\neg P \vee Q)$ is false, which contradicts our statement. Thus, Case 2 is also impossible.
Since the only two cases for the equivalence to be false are impossible, we  conclude that for all $P$, $Q \in \mathbb{B}.$ $(P \Rightarrow Q) \Leftrightarrow(\neg P \vee Q).$
Comment: Your teacher is **partially** right.  That is, your teacher's interpretation of the if and only if statement as two different implications, running in opposite directions is correct.  What your teacher failed to realize is that your work in each of Case 1 and Case 2 accomplished the same thing.  For example, by showing that it is impossible for (simultaneously) the left side to be true and the right side to be false, you are showing that the left side implies the right side, **as required**.   ...see next comment
Comment: So, ultimately, your work is valid and your teacher made a mistake in not realizing that.  I suggest that you print out this posting, including my comments, and show it to your teacher.
Comment: your proof is perfectly fine. your grader is wrong.
Comment: Your proof by cases is correct. Each case is in effect a proof by contradiction for the desired sides of the if and only if statement. Note: While your proof is valid, normally when doing a proof by cases - you want to exhaust every case, claiming that these are the cases that matter needs justification. Even if the other cases are trivial, you should write them out in a proof by cases.
Comment: Thank you guys so much! Will show this to the grader and my professor.
Answer: Your argument is perfectly valid, and your grader is illogical to claim that that bi-drectional derivation method is the only valid proof of an equivalence.
P.S. Regarding Michael's suggestion above to belabour the trivial cases, I feel that this is a choice depending on the agreed level of detail required, and that your final sentence, "Since the only two cases for the equivalence to be false are impossible" is sufficient unless your grader wants more (so yes, there is subjectivity here, but regarding the desired level of exposition rather than the validity of your proof).
P.P.S. Is there only one way to prove trigonometric identities?
Comment: Thank you so much!


How can we effectively teach schoolchildren theory?

Question: Background Reading: I thought it was worth extending the recent discussion about music theory to the topic of teaching theory.
I think our default approach to teaching theory is sometimes too disconnected from the actual music we play. I believe this is a contributing factor to the view that music theory is a bunch of useless rules invented by people who can't actually play music (disclaimer: generalisation and stereotyping intended).
So, how can we teach theory well? To make this question more specific, I'm thinking about school-aged kids, not university classes. They enjoy playing music, but don't have a burning desire to know the 'boring' theory. How can we show them that theory is useful, and can make music more enjoyable? What theory should we actually be teaching? How do we make it relatable and understandable?

As an example, here's a theory worksheet on perfect cadences. There doesn't seem to be anything horribly wrong; it explains what the cadence is, gives an example from Ode to Joy, and asks the student to write a few cadences. But I have this nagging feeling that a student will fill it out, get it 100% right, then think "Well, that was useless. Now I'm going to go and play Let it Go, and forget everything I ever knew about cadences." I worry that this style of teaching contributes to the devaluing of theory.
Comment: Thanks for posting this question. Of course personal opinions will feature, but it's too thought provoking - and will produce some inspiring answers - to be thrown out. I hope!
Comment: I love this question. I've been thinking about this a lot. Inexperienced as I am, I actually do have a "student," and I've been thinking about how I would explain some of these concepts in a way that would make her tick. I will be keeping an eye on this thread.
Comment: It's good to set in a student's mind that music theory that music theory is just a way to talk about music. It gives a way to answer (or try to answer) questions like "why does this note sound wrong?", "why does this section feel more exciting?", "why is this tune so catchy".
Comment: In your example, the teacher could play, "Let it Go", and change some of the cadences around and see how the students feel about them: Take a piece that the student cares about and show them what's interesting about it from a theory point of view.
Answer: Teach students how to make music that they like.
While experienced musicians are often very broad-minded, seeing value and beauty in many kinds of music, younger kids are often primarily interested in finding out about the things they like. Can you convincingly explain the structures of the songs in the charts/clubs/on your students' phones now? Could you make music like that yourself? If not, learn to do it before you try to teach it.
Introduce your students to the world of music - in a balanced way.
It's great to learn about European art music from two or three hundred years ago. It's just as important to learn about Latin dance, Arabic scales, and Japanese folk music. It's as important to learn about timbre and rhythm as it is to learn about harmony and melody.
Introduce your kids to as many concepts as you can, and let them decide which ones they find useful and relevant to what they want to do.
Help your students understand what the different parts of music theory represent.
In particular, they should understand which ideas are...

Terminology and notationThese will offer ways to relate and communicate musical concepts.
Style-specific rules and guidelines The fact that these are style-specific needs to be understood.
Fundamental musical concepts Don't be scared to get into the science of frequency ratios, the harmonic series, wave-forms, psychoacoustics - even the evolution of the auditory system. This is the stuff that will inspire your brightest students!

Teach your students to think 'theoretically' outside of the theory they already know.
You could play them a piece or two that you think they might be very unfamiliar with, and ask them to write down what they think are the musical rules of that piece or style - then get them to follow those rules to make a new piece in that style. It's when doing something new that thinking theoretically can be most useful.
Don't "teach them theory" at all - give them the opportunity to experience music, inspire them to think about it, plant the seeds of the theory knowledge and let it develop and grow organically.
Answer: There are two ways of approaching music theory - as a music theorist (who may or may not actually play) or as a music practitioner (that is: a musician). The knowledge requirements are obviously different and in the context of this question I will focus chiefly on the practitioner's perspective.
Let's think about what (some) knowledge of music theory is worth to a musician. I can see at least three reasons to learn at least some theory:

Communication with other musicians,
Pattern familiarization,
Creative shortcuts.

Let's take a look at each of them in turn.
Communication

Let's give it a name, so we can have conversations about it.

(the Mighty Mighty Bosstones on the origin of the term skacore)
As musicians we need to be able to talk about the finer points of music with other musicians and everyday language is not always up to the task. Sure, you can say "play this very quietly", as opposed to pianissimo, but most times the only alternative to standard musical terms that signify what you want ("play this bit with a 6/8 feel", for example) is to actually demonstrate what you're trying to say. Clearly, being able to express a potentially complex concept with a simple term is preferable.
Since we're talking about teaching, the two musicians who need to communicate are the teacher and student. It is, of course, possible to teach someone to perform a musical piece without addressing theory at any point (simply by demonstrating all the motions the student needs to go through in the context of the performance), but it will go a lot quicker if you are able to communicate on a conceptual level. Lest we forget, such basics as note names and musical notation are also parts of music theory.
Pattern familiarization
We can look at a piece of music as a long series of notes and rests that get us from the beginning to the end - and even learn to play by memorizing it as such, or we can look at it as construct made up of smaller building blocks. Crucially, these building blocks will appear in other music as well.
What kind of building blocks? Scales, chords, arpeggios, sequences, rhythmic patterns, standard forms, cadences etc. Everytime we are able to spot something we already know in an otherwise unfamiliar piece of music, our work becomes that much easier. Rather than examining and learning each note in turn, we can instead apply higher-level concepts that we are already familiar and proficient with.
In order to become familiar and proficient with such "building blocks", however, we must first become aware that they exist. One of the functions of music theory is identifying such building blocks, naming them and examining how they fit together.
Creative shortcuts
Sooner or later, we may find ourselves needing to actually create some music, as opposed to learning what someone else has written. This may be as involved as writing an entire piece from scratch, or as simple as "could you come up with a part over this bit?"
Again, it is possible to do the work by trial and error. However, it will be quicker and easier if we have an idea of what is likely to work and what isn't - if we are familiar with the options available to us and what they sound like.
A knowledge of music theory allows us to both become familiar with such options and to learn a system of classification that makes it easy for us to keep track of them.
A practical approach to teaching music theory
With the above in mind, two things become apparent: that it will be highly useful to the student to learn at least a bit of music theory; and that learning the theory should be subservient to the learning of musical practice.
In other words, the student should, first and foremost, be learning to perform music. However, as they learn to play, they should also be gradually learning what it is that they're playing and how it fits in with other things that they have already learned.
Let's try to compile a list of the most basic music theoretical concepts that every student should learn:

A solid knowledge of rhythm (including rhythmic notation) is an absolute must for everyone. I always say that learning to count is the most important skill to master as a musician.

The great thing about rhythm is that it is a skill that can be practiced from day one, even when the mechanics of producing sound from an instrument are still a deep, dark mystery. In my teaching practice, I have always started out my beginning students on clapping exercises, letting them get a feel for rhythm without having to deal with the fiddly motions of playing an instrument.

The basic names of the sounds one is learning to produce should be taught at the earliest opportunity, though probably no sooner than when the student is first called upon to play them.

Students should be learning the names of the notes they play (trivial, I know, but nevertheless important), chords (especially with pattern-intensive instruments, such as the guitar), articulations and so on (specifics will depend on the instrument).
The reason for this should be clear: the student will be called upon to play these things over and over again in the course of their study. The teacher needs a concise way to communicate what the student needs to play and it is much easier for the student to be thinking along the lines of "here I'm playing the C major chord", as opposed to "I need to put this finger here and this finger here and that finger there and..."
It is also likely that the student will at some point in the future find themselves playing with others outside the classroom and here the ability to have meaningful conversations about what is to be played will be invaluable.
Teaching some appropriate form of musical notation is to be encouraged with regards to this particular issue. It need not be standard musical notation from the beginning, if a simpler commonly used system exists (I am thinking of tablature especially, in this case, because it offers an unambiguous notation system for an instrument where the same note can potentially be played in six different places, or more). The point is for the student to have some way of taking notes of what they need to play, for when they don't have a teacher to show them, and to be able to explore written music on their own.

As the student learns to play, they should also be developing a mental framework that allows them to understand what they're playing and how it fits in with what they already know.

Faced with an instrument we are presented with a sea of musical possibilities. We need a way to break them down into bite-sized chunks.
Each instrument has its own set of "tricks" to make it easier (for example, the piano keyboard lets one "see" the note names; the guitar, on the other hand, makes it easy to transpose music to different keys, by shifting fingering patterns to different position), so specifics will depend on what is being taught.
On the other end of the spectrum, there are things universal to all (or most) instruments: things such as musical form, tonality, rhythmic templates.
In the context of such a framework, it is possible to isolate concepts common to a large number of specific pieces and to practice these in isolation. If we know how to play a C major arpeggio, say, we can fall back on this knowledge whenever we encounter it in a hitherto unknown piece of music. We can practice it in different keys, building up mechanical proficiency (that is: proficiency with the movements needed to execute a musical passage) and preparing ourselves for a time when we're required to play it in a musical context.
In all cases, however, we must first become aware that such methods for breaking music down exist, before we can turn them to our advantage.
General considerations
As previously stated, for a musical practitioner, playing should come first. Theoretical concepts need only be brought into the picture as they appear in the music the student is learning to play.
All things rhythm will need to be introduced pretty much from the beginning, even if we begin with something as simple as playing (or clapping) quarter notes while counting "one-two-three-four".
Similarly, as the student is learning to play individual notes or chords, we should be introducing the names we will henceforth be referring to them by. The ability to say "now play a B note", as opposed to "play with that finger there", is so important it is scarce worth mentioning. If the student is playing chords, they should know what those chords are called - with several notes being played simultaneously, the ability to "dump" a large amount of information into a single name is that much more important.
Once the student has a grasp of the basics, and learns to play some simple pieces, we can gradually introduce higher-level concepts. Musical form is something that is often forgotten, when we think of music theory, but it is both crucial to mastering longer and more complicated pieces and a fairly simple concept even for a beginner. By demonstrating how a seemingly monolithic piece of music can be broken down into "chunks" that are repeated and intertwined we are showing the student how to make their work of learning a new piece easier.
When the student begins to expand into different keys, we should be gradually explaining how the concept of keys works and how the various parts of the tonal system (scales, chords, cadences) can be isolated, practiced and applied. The goal is for the student to look at a piece of music and think less in terms of a long series of notes, but rather in terms of musical blocks that they can spot, identify and know how to play.
Practice makes permanent, so it is important to keep reinforcing these concepts in the course of our teaching. The student should learn and practice these elements of musical theory until they become ingrained. The easiest way to do this is to guide the student through analyses of the music they play - especially new pieces, once the student has a fairly good grasp on what they've been taught so far. Remember, the goal is to make it easier for the student to apply things they already know and can play in the context of learning new music.
From a teacher's perspective, this means we should be approaching our lessons analytically as we prepare them. We should have a solid idea of the theoretical concepts present in the music we will be teaching the student and look for ways that we can exploit them to the student's advantage.
Does a piece contain some concept the student is familiar with? Make a note of it and point it out.
Does it share a concept with other music the student already knows, that would make learning easier and faster? It may be time to introduce the concept and show the student how it is applied.
Have you already equipped the student with an analytical toolkit of their own? Great! Begin the learning of new music by looking over the score with your student and discussing all the places where the student can apply their existing skills.
If we want our students to take away a knowledge of musical theory that will help them with their musical practice, it should be clear that we need to examine our own. I firmly believe all teaching is also learning (Schoenberg seems to agree). Can we go beyond teaching our students how to play a specific piece of music, towards building skills and knowledge that will allow them to play different things with the minimum amount of extra work? If not, perhaps it is time to brush up on our music theory.
Edit: an illustrative example
After I posted this answer, I got to thinking that it could do with an illustration of the final goal we might hope to achieve in teaching theory to practitioners and it so happens I have a good personal anecdote.
At my sister's wedding I was asked to sit in with the band as a lead guitarist. They were playing a bunch of appropriate standards that I was familiar with, but had never played before. They asked me briefly before going on stage, so any kind of rehearsal was out of the question.
Luckily, the keyboard player had some brief notes (basically, chords and lyrics), so we'd agreed I'd just be looking over his shoulder. Then he tells me:
"There's just one thing: I'm transposing my keyboard to make my life easier, so the actual keys I'll be playing in will be different."
No worries.
What I'd ended up doing is having him tell me the actual key before he started a song. Then I would mentally apply a quick Roman numeral analysis to the chords he had written out to get an idea of where I am, harmonically, and that would give me an idea where I had to go melodically. Worked out rather well.
The moral of this story is that in order to pull it off, I had to go beyond what information I was presented with (which was both incomplete and not quite accurate). The only way to do so was to first isolate the general concept and then come up with an appropriate application, in terms what I actually played. Without a solid grounding in basic music theory (or a quick ear and perfect pitch) it would have been impossible.
Comment: Working on the mental model is crucial, I think. Maybe a top-down approach could serve it better because as listeners we start to get familiar with higher level things of a song (the tone, the mood, the rhythm, how it is constructed (verse, chorus, etc.)).
Also, a teacher must make sure that theory is mapped down and rooted to hearing: I have seen guitarists who did not hear or know which notes were played over kick drum or snare - so sometimes the drummer had to follow the player, who could count, but won't feel.
Comment: @atoth I'd venture someone who can't play over a (relatively stable) drumbeat doesn't, in fact, know how to count. How can we count if we don't know where the ones are? W/r/t top-down, I'm not convinced TBH. I wouldn't try teaching basic essay form to someone learning to write their first words, much less, learning the alphabet.
Comment: What you say sounds logical, but on the other hand I have encountered a lot of people who could count from 1 to 8 but were failing at finding the correct emphasis (is it 2-4 or 1-3?). Also we know of many people who are capable of "speaking essays" without knowing the "alphabet". It is the teacher's responsibility to check and verify if the dots were connected. The goal (e.g. playing on time) can't be the side-effect of a method.
Answer: Yout hypothetical student is correct, in the sense that "understanding perfect cadences" well enough to write a few of them in four-part harmony is a completely useless piece of knowledge except in certain musical contexts, and those contexts are most likely of minimal interest to him/her at this stage in his/her musical development.
The "traditional" approach to teaching "music theory" at an elementary level seems to be based on common practice harmony. Back in the 19th century that was a "live" musical context, but not any more. Even in the context of teaching the performance of "classical music" (whatever that is!) on "traditional musical instruments," there is at least a century's accumulation of good quality practical teaching material that lies outside it.
If the above correctly identifies the root (or at least one root) of the problem, I don't have a "solution" - but as a specific example to focus on, what would a "theory course" for keyboard students, designed to be used in parallel with Bartok's "Mikrokosmos," look like? I suspect "perfect cadences" would not feature very strongly in it.
And "Microkosmos" is hardly cutting-edge avant garde music, in 2016...
The various "elementary theory and musicianship" books by Hindemith were at least a start in the right direction - though they are now more than half a century old, and arguably Hindemith had his own theoretical axe (which never became a mainstream tool for music making) to grind while writing them.
Answer: (Let me begin by saying that that is an awful music theory assignment that you showed. I know it's not yours, but I would hate music theory if that's what I learned from as a student!)
First we have to define exactly what we mean by "music theory":

Is it music theory for classical musicians, or music theory for popular musicians?
Can the students read music, or are these students that only want to compose electronic music on their computers?
Will the curriculum include an aural skills component, or is it strictly written theory?
What is the overall output goal for which the student is learning (and the teacher is teaching)?
Do you prefer a more "vertical" chord-stacking approach (see the Kostka and Payne textbook) or a more "horizontal" voice-leading approach (see textbooks by Aldwell and Schachter; Laitz; and Clendinning and Marvin)?

Only then can we really start to answer this question.
And in addition to the two great answers already given from alephzero and topo morto, some further remarks:

Instructors must understand the distinction between and importance of contextual versus acontextual examples. By "contextual," we mean an example that comes from the literature (like the "Ode to Joy" example in the PDF you provided). By "acontextual," we mean examples outside of the repertoire (like the remaining two pages of "complete these authentic cadences" in the PDF). Students prefer contextual examples the overwhelming majority of the time, and the material "sticks" much more easily when you use actual musical examples.
Similarly, meet them in the middle when it comes to the repertoire you discuss. Too many music theory instructors insist on teaching the same phrases from the same Mozart and Haydn piano sonatas over and over again, and nothing kills a student's enthusiasm faster. If your repertoire doesn't include examples from Aladdin, The Beatles, and Lady Gaga, you're just plain doing it wrong.

Lastly, some sources on teaching music theory, even though they're both geared towards college professors:

Michael Rogers's "Teaching Approaches in Music Theory" is a must-read for anyone seriously teaching music theory.
If you're teaching aural skills, also check out Gary Karpinski's "Aural Skills Acquisition."
There is a journal dedicated to this very question: the Journal of Music Theory Pedagogy. Most of these (freely available) articles are far beyond the scope of your question, but it's an important source for anyone teaching music theory.
Comment: I agree with you entirely on the theory example I gave; I found it randomly through Google, and didn't want to be too nasty. I wouldn't use it, but I do see similar examples being used all the time.
Comment: I figured as much. Unfortunately, there are a *lot* of bad music theory teachers out there...
Comment: Actually someone tried to analyze the Lady Gaga songs :) http://www.slate.com/articles/arts/culturebox/2014/03/lady_gaga_s_bad_romance_owen_pallett_explains_the_pop_diva_s_genius_using.html
Answer: I'm that awkward violinist who didn't know a lick of theory -- and didn't care to -- until about two years of playing, and really still didn't care to until he took up piano. Why piano? Well, think about it from the green-horn violinist's perspective. The violin is pretty abstract when it comes to music theory. The notes are basically points on a string that you need to memorize -- physically and sonically. Because of this, it's usually easier to learn with a method like Suzuki, where you become proficient technically fairy quickly, but at the expense of reading music.
It's the only reason I'm here typing this today and not playing video games, if that makes sense. I would have quit years ago.
Because of Suzuki, I could enjoy the violin sooner than I would have otherwise. But... Theory. Yes. I couldn't read music at all until about two or three years into playing, and very poorly until I joined my first orchestra. So, about a year or two ago, I took up piano "for the theory" and as a supplement to the violin.
IT WAS PAINFUL. SO PAINFUL. (At first...)
Because I had never played before, and my piano teacher didn't really know any other curriculums that well, I started with a book that was basically geared for a kindergartener. I was fairly proficient at sight-reading at that time, but I literally got no joy from playing "The Computer" or "The Watchman," or even "classics" like the "Boogie Woogie Goose." I like pre-modern stuff the best.
Then, not that long ago, my teacher started showing me how to improvise hymns.
The beauty of it. Wow. My musical world had opened up. I no longer viewed music as prewritten notes on a page. Suddenly, the world of composition, and improvisation had appeared in front of me.
All of the sudden, I wanted to learn about chord progressions -- things that would never have mattered to a violinist. I wanted to learn about melodic decorations.
My teacher started by showing me how to find the "chords" of a song. Find the key signature, pick the first note of the scale, make your triad, repeat for the fourth and fifth notes of the scale, and you have three chords that sound delicious in this key.
"Yay!" I thought. "Now I can play any song I have a mind to! I can improvise!"
Take a different situation.
"Alright, child. Today, we're gonna learn about CHORD PROGRESSIONS! Isn't that exciting?"
[Blood curdling scream, rips hair out]
I didn't even realize I was learning that stuff. I was taught it as a way to make music, in the context of making music.
I've since then pursued music theory more independently, but my teacher has taught me how to roll out chords (1, 5, 8 + 3 + 3... I wouldn't care that much if I couldn't apply it to my own music), and I learned about melodic decorations on my own time... I'm learning music theory because I see how I can apply it in the context of entertaining myself.
When I'm in a bad mood, or bored, or happy, or sad (or basically whenever I walk past the piano) I sit down and improvise. I can apply it. Anything that pertains to it, I want to know.
What about reading sheet music?
I figured out that I can have a whole orchestra in my backpack whenever I have a score with me. I teach myself songs, and enjoy lording my proficiency over my less sheet-savy friends.
Entertaining, huh?
All of this stuff, if taught in a text-book format, would be in one ear, and out the other.
Here's my proposition:
Music Theory on a need-to-know basis, and by need, I mean want.
Tell the kid, "Hey, today we're gonna look at a couple of cool songs that use [blank]."
"Sounds cool, huh? Did you know that you can throw [blank] in wherever you want? Yeah, I think it's neat too. Let's try some. Here, stick it in this piece."
Or, if [blank] can't go wherever, show the child all the places in songs that he likes that [blank] appears.Most importantly, show the kid that he can use [blank].
There is the occasional item of theory that's so theoretical that it can't really be applied in everyday usage, but the student will be motivated once he finds the reason, even if you can't show it to him.
I've begun the menial task of memorizing my key-signatures. It's hard, and if I had been forced to do it before, there would be many a tear shed -- and key signature forgotten.
Now I want to learn them, because I want to point at a scary looking score and say, "That's F Minor!"
There's my ten cents.
Comment: You've talked about part of 'your journey' and that's always something worth remembering... that any student is *somewhere* along a long journey, and it's worth working out roughly where they are!
Answer: I think the great (re-?) revelation of our age is the importance of motivation in learning and playfulness.
Motivation
If you are a songwriter you will probably learn theory because of curiosity and to write better songs. Those who are in a big band needs to know how to read sheet and improvise. Your friend next door only wants to listen and play songs he hears on radio, so he needs only ear training and basic scales/chords.
All these people would need different approaches. If they get what they need maybe their natural curiosity kick in and will learn more.
Also people from different genres may not like to learn a totally different genre at first. (I really hated to play boring classical guitar compositions in C major - just to learn sheet reading)
Games
Why should learning be a pain? Just imagine a fantasy game, for example, where you can cast different spells by playing different scales. You made learning scales fun and effective and enjoyable.
If you ever played a strategic game you probably had learnt a lot about managing resources, constructing machines, etc. All by a side effect of a fun experience. Now I would be really happy to play games that teach me music theory or train my ear.
Providing tools to the user of theory
As I said in motivation, you should have multiple kind of courses for different needs. For example as a songwriter the ideal approach of learning music theory would be a searchable "database" of notation, theory and musical examples combined to each topic - so I can search for the next step when I write a song (examples):

convincing key changes
gluing parts rhythmically together
writing vocal harmonies
turning up the heat emotionally (tricks on drums, orchestration, harmonies)

etc.
Without opinions ("4 note chords are more sophisticated than playing triads"), but with lots of playable examples, preferably multiple genres and countries.
Never forget that music meant to be heard and understood sonically.
The power of community
You are not alone. There already really nice materials on YouTube from you can learn how to teach best a certain area if you are open. There should be music-loving developers who would love to work on a music teaching related fun app for a phone. There are forums you can try and test your teaching methods.
Answer: You take a leaf from the best composition teacher of the last century:

Dieses Buch habe ich von meinen Schülern gelernt. Arnold Schoenberg, Preface to Harmonielehre, 1911.

"I have learned this book from my pupils."
Schoenberg's style of teaching was exploratory: if you look through his theoretical and didactic writings, there are ample examples from the literature. The nature of this exploratory style of teaching is to involve the students in working out how real music works. Doing it this way absolutely requires you to refine your own understanding of the music as you teach it, frequently through the insights of the students themselves. It certainly requires you to refine your approach as you see what works and what doesn't.
Translating this approach to schoolkids isn't all that different from teaching 19-year olds: you need to relate it to what they're doing (which, in the case of schoolkids, is learning to sing and/or play progressively more complex pieces). It becomes a case of "Hey, when it sounds like we should take a breath, that's a phrase. Now, look at what this piece and this piece do when the phrase ends..."
Pace alephzero, you do need to work from a basis of common practice. So much of modern and postmodern music takes its departure from it, and, frankly, most of what schoolkids will be learning to play on their instruments is quite likely to be from smack dab in the middle of that period, not Mikrokosmos.
This is also taking a leaf from the great Modernist: the man who taught composers as diverse as Webern and Cage taught almost exclusively common practice theory. There are a couple of reasons for this:

It is easier to come to conclusions about music that is primarily from the past. There has been more time and effort spent in figuring out its workings.
Because it has been codified to a greater extent, it is more apt to the task of developing the student's ability to manipulate tones to do what he/she wants them to do - musical "calisthenics", if you will. To accomplish this task, you need to set clearly limited goals for the exercises lest you swamp the student with too many poorly understood decisions to make. Modern music is by no means as well understood or codified, so the problem of forcing decisions prematurely becomes that much greater. This isn't unlike fine arts: if you master a basis of life drawing and perspective, you can do pretty much anything you want afterwards. You have the necessary skills and control.

Myself, when I'm dealing with younger students or beginners, I like working with Schoenberg's Fundamentals of Musical Composition as a guideline: a logical progression through the elements of music, all related to scads of examples taken from real music (and the examples written specifically to make a point also make real music).
Comment: @GeneralNuisance, so long as people bear in mind that at least half of his output was tonal (even into the 12-tone years), and that it was *very good* tonal music. My own standing joke is that Schoenberg was Wagner's best work: just have to listen to the Gurrelieder to understand where AS was coming from.
Comment: Yes, Schoenberg was great. Writing music by almost randomly selecting tones. What artistic... vision? (Just kidding, I like some Schoenberg stuff, but *somebody's* gotta make fun of him.)
Comment: When you say that 'Modern music is by no means as well understood or codified' - what period are you thinking of? And are you referring to particular styles?
Comment: @topomorto, pretty much anything after 1911. If you listen to, say, AS's free atonal pieces, mid-period Bartók, and Roslavets of around the teens and '20s, you realise that they have a fair bit in common, and that Forte's set theory (which is the only one that nominally covers all of these) does a not very good job of explaining what seems quite functional about them. If you listen to classic twelve-tone music, you realise that the theory does a piss-poor job of explaining *Lulu* or AS's Piano Concerto. Theory from that period is really ad hoc, and that still remains true for today's music.
Answer: It is important for people to realise that music just like any profession has a professional language. Training in music theory is also a training in a musical language, so that the candidate hears another musician say things like 'modulating to the dominant' the candidate actually understand what that means.
It is also an education in how music is notated, the really eloquent way in which the world has devised a system that people can understand and perform music to a remarkable manner of uniformity. Regardless of nationality, religion or language.
If a person wants to play someone else's music or have a way to get his/her music performed by someone else then there is simply no other way to convey these concepts but by these forms of notation.
It is also worth noting but people cannot seem to accept it, but music just like any other art can be studied in a scientific manner. Art is not just something that the muse or god has bestowed upon a chosen few, it is something you can work on or at. You can train at it, you can practice it.
Music is ultimately nothing more than a trade. The heights of art in the Renascence was brought to the world by the guilds, which among other things where a trade-school for the arts
It is a skill that you can develop and ultimately it is a skill that anyone can do. Some people find music easier than others, but ultimately success boils down to the ability of the candidate to motivate him or herself, not by anything he or she is born with. Believe me when you are at conserve and you have to do your performance exams on a 07:30 winters morning you have to be really dedicated to do it well.
It is a test of will-power, of work-ethic and of hard-work
Music Theory is the centuries worth of exploring into what makes music good? What makes a catchy tune Franz Listz asked himself that question just as many times as David Guetta did?
You know I just graduated from Conserve, but I would really like to be able to buy myself food, how am I going to sell my music effectively. Chopin asked himself this and so does Taylor Swift.
That is why we study music theory, so that the trade of music, theoretical underpinning are made clear to us


Dirac delta and test functions

Question: By the use of the test functions prove that:
$$f(t) \delta '(t) = f(0) \delta '(t) - f'(0) \delta(t)$$
Attempt:
I want to use some test function $\phi (t)$. So starting from
$$\langle f \delta' , \ \phi \rangle = \int^\infty_{-\infty} f(t)\delta'(t) \phi(t) \ dt$$
Using integration by parts:
$$= \Big[ f'(t) \delta (t) \phi (t) \Big]^\infty_{-\infty} - \int^\infty_{-\infty} f'(t) \delta (t) \phi'(t) \ dt$$
I'm stuck here. The aim is to arrive at $\langle f(0) \delta' - f'(0) \delta, \ \phi \rangle$.
I am not sure how to proceed. I think I will need to use the $\langle \delta, \phi \rangle = \phi(0)$ property at some point.
What do I need to do?
Any help is greatly appreciated.
Comment: The boundary term will vanish due to the nature of $\phi$, and you seem to have used the product rule wrong, you should have $f'\delta\phi+f\delta\phi'$ not $f'\delta\phi'$.
Answer: I guess you are using physicist's notations, however the dirac distribution is not associated to a locally-integrable function.
Actually using the definitions, we get quickly the answer. Let $\varphi$ be a test function, one has : $$\langle f\delta', \varphi \rangle=\langle \delta', f\varphi \rangle = -\langle \delta, (f\varphi)' \rangle = -\langle \delta, f'\varphi \rangle-\langle \delta, f\varphi' \rangle= -f'(0)\varphi(0)-f(0)\varphi'(0).$$ But $$f'(0)\varphi(0)=f'(0)\langle\delta,\varphi \rangle$$ and $$f(0)\varphi'(0)=-f(0)\langle \delta',\varphi \rangle,$$ hence $$f\delta' =f(0)\delta'-f'(0)\delta.$$

Dirac delta and test functions


Gettextbounds in android

Question: We used to find the rectangle which fits the given text, for example if give "TESTING" in gettextbounds api it will give a rectangle that fits the given string "TESTING", but could any plz clarify on which basis the rectangle length is calculated, whether the font size will be considered if so is it possible for me to check like this ?
1) Way i tried
        CharSequence text = getText();
        canvas.drawText(text, 0, text.length(), mTextX, mTextY, getPaint());
    Paint pt = new Paint ( );
    pt.setTextSize(10);

    TextPaint tp = getPaint();
    String string = "haa";
    Rect currentBounds = new Rect ( );
    //this.setTextSize(/* TypedValue.COMPLEX_UNIT_PX */ 10, /* fontPixelSize*Home.fltFontRatio */ 32);

    tp.getTextBounds((String) text, 0, text.length(), currentBounds );

    Log.e ( " ", "Desired Text " +text);
    Log.e ( " ", "first Ondraw Left " +currentBounds.left);
    Log.e ( " ", "Ondraw Top" +currentBounds.top);
    Log.e ( " ", "Ondraw right " +currentBounds.right);
    Log.e ( " ", "Ondraw bottom " +currentBounds.bottom);

    pt.setTextSize(20);

    tp.getTextBounds((String) text, 0, text.length(), currentBounds );

    Log.e ( "", "Desired Text " +text);
    Log.e ( " ", "Second Ondraw Left " +currentBounds.left);
    Log.e ( " ", "Ondraw Top" +currentBounds.top);
    Log.e ( " ", "Ondraw right " +currentBounds.right);
    Log.e ( "Nrace ", "Ondraw bottom " +currentBounds.bottom);

2)  Second way i tried
    TextPaint tp = getPaint();
    String string = "haa";
    Rect currentBounds = new Rect ( );
    this.setTextSize(/* TypedValue.COMPLEX_UNIT_PX */ 10, /* fontPixelSize*Home.fltFontRatio */ 32);

    tp.getTextBounds(string, 0, string.length(), currentBounds );

    Log.e ( " ", "first Left " +currentBounds.left);
    Log.e ( " ", "Top" +currentBounds.top);
    Log.e ( " ", "right " +currentBounds.right);
    Log.e ( " ", "bottom " +currentBounds.bottom);

    this.setTextSize(/* TypedValue.COMPLEX_UNIT_PX */ 10, /* fontPixelSize*Home.fltFontRatio */ 10);

    tp.getTextBounds(string, 0, string.length(), currentBounds );

    Log.e ( " ", "Sefond Left " +currentBounds.left);
    Log.e ( " ", "Top" +currentBounds.top);
    Log.e ( " ", "right " +currentBounds.right);
    Log.e ( "", "bottom " +currentBounds.bottom);

In the above two methods am trying to find out the various rectangle size for the given text size. if this is not a good way plz advise me by posting some sample codes. Simply to say i have to find the various rectangle which fits the text "TESTING" for various font size.
Thanks in advance.
Answer: I find this part of the API quite confusing, however I think I almost understood how it works. A call to getTextBounds() returns the smallest rectangle that would enclose all the characters drawn by a subsequent call to drawText() with x=0 and y=0. This is stated in slightly different words on the API reference. Everything that is in Paint and could affect the appearance of the text is taken into account. Here's an example:
Rect bounds = new Rect();

Paint paint = new Paint();
paint.setTextAlign(Align.LEFT);
paint.setTypeface(typeface);
paint.setTextSize(textSize);
paint.getTextBounds(text, 0, text.length(), bounds);

The reason why the rectangle has such exotic coordinates is because when you draw text with drawText(), the origin to which x and y are relative depends on the typographical properties of the Paint that you selected. For instance y is relative to the baseline, which is neither above nor below the font, but usually strikes it somewhere across the middle. For this reason the bounds rectangle will have (usually) a negative top and a positive bottom. The negative top means that the top of the text is above the baseline (y decreases going up), while the positive bottom means that the bottom of the text is below the baseline (y increases going down). It is interesting to note that when you measure a string such as "Hi" the bottom is likely to be 0, because those characters do not have a below the baseline part. On the contrary, when you measure a string like "Hg" you are likely to get a positive bottom, because the story of the g is below the baseline. I'm not sure how the horizontal position is estimated, though.
With this said, to draw the text of which you have computed the bounds you can do:
canvas.drawText(text, -bounds.left, -bounds.top, paint);

This will draw the text near to the upper left corner of the canvas. The coordinates of the upper left corner are (0, 0) so to move the text around you only have to add your desired amount of displacement:
canvas.drawText(text, -bounds.left + yourX, -bounds.top + yourY, paint);

Another example: if you want to create a bitmap that contains text, and you want to fit exactly the available space, you can do:
Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, -bounds.left, -bounds.top, paint);

If you want to leave a few pixels to the left, right, top and bottom, let's say 2, you can do:
Bitmap bitmap = Bitmap.createBitmap(bounds.width() + 4, bounds.height() + 4, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, -bounds.left + 2, -bounds.top + 2, paint);

Comment: I've been experimenting with this a few other times, and I'm pretty sure that the answer is correct. Did it work for you? If that's the case maybe you could accept the answer, it may help other people in the same situation.
Comment: That is probably the problem mentioned in http://stackoverflow.com/questions/7549182/android-paint-measuretext-vs-gettextbounds?lq=1 however the question asked about  **getTextBounds** and in particular to *clarify on which basis the rectangle length is calculated, whether the font size will be considered if so is it possible for me to check like this*.
Comment: Doing exactly as stated in this answer doesn't work for me, it's still a few pixels out sometimes. However, using `Paint.measureText()` always works.
Comment: Informative info about getTextBounds, thanks. Though for anyone who comes here, Alex Chi's looks like a more reliable solution, since it uses measureText to get the width. (and as OP said "if this is not a good way plz advise me")
Comment: Ah, Prizoff explains http://stackoverflow.com/a/15398496/199364 what is not made clear in this answer. To correctly measure needed width using bounds, must do `bounds.left + bounds.width()`. Perhaps `left` is slight empty space before first visible pixel, and `width` is the width of the actually drawn pixels.
Comment: you define well, there is a shortcut for this  try setting paint.setTextAlign(Align.RIGHT); and we are good to go.
Answer: There are some nuances, so it is better once to see...
Red rectangle shows text bounds, x,y - any coordinates (of left lower point of the text bounds)
Rect textBounds = new Rect();
Paint textPaint = new Paint();
Paint rectPaint = new Paint();
String text = "java m";

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    textPaint.setTextSize(100);
    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, x, y, textPaint);

    rectPaint.setColor(Color.RED);
    rectPaint.setStyle(Paint.Style.STROKE);

    canvas.drawRect(
            x,                       // left
            y - textBounds.height(), // top
            x + textBounds.width(),  // right
            y,                       // bottom
            rectPaint);
}

text = "Hello Worlds"

text = "java m"
Comment: Paint.Align textAlign = Paint.Align.LEFT; should be this in this case.
Answer: Here's a way that works for me: use Paint.measureText(text) to get text's width and Paint.getTextBounds(text, 0, text.length(), bounds) to get text's height (height = bounds.height())
Answer: My solution:
class Pos {
  public int X;
  public int Y;
}
public static void getTextPositionAndRealBound(Paint paint, String text, int x, int y, Pos pos, Rect bound) {
  paint.getTextBounds(text, 0, text.length(), bound);
  // in X
  bound.left = x;
  bound.right = (int)(paint.measureText(text) + 0.5); // .5f to 1

  // in Y
  y = y - bound.top;
  bound.top = y;
  bound.bottom = bound.height();

  // reset the position
  pos.X = x;
  pos.Y = y;
}

You know that the X is right and the Y is down in the coord of the bound by getTextBounds.
The solution can get the position and real bound of text. You can move the text to any position, just edit the var - pos and use it when call Canvas.drawText like this:
Pos pos;
Rect bound;
getTextPositionAndRealBound(paint, text, x, y, pos, bound);
canvas.drawText(text, pos.X, pos.Y, paint);

Note: thanks for @ToolmakerSteve advice
Comment: If calling repeatedly for different texts, is important to initialize pos.Y before each call, since this method alters it. Such is the danger of modifying input parameters. IMHO less risky is `(Paint paint, String text, int x, int y, Pos outPos, Rect bound)` where `x` and `y` are desired location. Then `..getTextBounds(..);  outPos.x = x; bound.left = x; bound.right = ..; outPos.Y = y - bound.top; bound.top = y; ..`  Note that there is no longer a local declaration `int y`, because we pass `y` in directly.
Comment: @ToolmakerSteve Right, I believe you are professional in Java. I will modify it. Many thanks.

Gettextbounds in android


site contact form not working

Question: My hosted site's contact form is not working. I have checked all the obvious things like:

correct site email address.
permissions
spam box

It is working on the local development machine. I contacted the hosting company various times with no luck.
I have also dropped a PHP mail script into the root and calling it directly works. So PHP's mail function works, just not my contact form.
So my question now is, what alternatives can I explore, bar getting the co-operation of the hosting company, to fix this.
Comment: "not working" is perhaps the single least helpful problem description there is. It gives us practically _nothing_ to work with.
Comment: what are logs saying?
Comment: The question was not so much about getting to the root cause of the contact form not working, but about alternatives which @terrycb neatly answered.
Answer: Since your question is about what alternatives you could use, have you tried the PHPMailer library?  Here it is: https://github.com/PHPMailer/PHPMailer
Another alternative could be the Mandrill API. You could add a custom submission handler to your contact form, and in that, make your API call to Mandrill.
Just for sake of completeness, here's how I would approach it (using the Mandrill PHP wrapper):
<code>//mymodule.module

require DRUPAL_ROOT . "/Mandrill.php";

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == "my_contact_form"){
    $form['#submit'][] = "mymodule_api_submit";
  }
}

function mymodule_api_submit(&$form, &$form_state){
  $mandrill = new Mandrill("PUT_AN_API_KEY_HERE");
  $message = array(
  'subject' => 'Test message',
  'from_email' => 'firstname.lastname@example.com',
  'text' => 'Message!',
  'to' => array(array('email' => 'email@domain', 'name' => 'TheirName')),);

  $mandrill->messages->send( $message );
}
</code>
I hope this helps.
Comment: Brilliant. I installed PHPMailer and used Google Mail. Works like a charm!

site contact form not working


Need 2 calculations explained

Question: This is math 101 but I am struggling to fully comprehend the difference between these 2 calculations.
I have 50 observations of the value of sales and volume of sales (in lbs). Price per unit = value/volume.
If I calculate the price for each observation, sum, then divide by the number of observations, is this a weighted average?
If I sum all observations of value of sales and volume of sales, then divide the two, am I calculating a simple average price?
What am I calculating in each instance and why are they different?
Comment: A good way to see it is to do only two observations.  Make up the data with very different volumes and rather different prices. Do the two calculations and think about what is being divided by what.
Answer: Let's write out what you are computing.  Suppose your data is $$\{S_i,V_i\}_{i=1}^{i=50}$$  Of course $P_i=\frac {S_i}{V_i}$
What are your two procedures? Assuming I have understood you correctly we have:
Method I: $$\frac {1}{50}\sum_{i=1}^{50}\frac {S_i}{V_i}$$
Metod II:  $$\frac {\sum_{i=1}^{50} S_i}{\sum_{i=1}^{50} V_i}$$
Phrased this way, it's clear that they are not equal in general, no?
The big difference, to me, is that method II is dominated by the big volume days whereas method I is not.  As an example, suppose you only had two observations:  $$\{1,1\}\;and\;\{2^*10^6,10^6\}$$  The price for the first day is $1$ and for the second day it is $2$, hence Method #1 gives $\frac 32$.  But method #2 gives:$$\frac {2,000,001}{1,000,001}\sim 2$$.  As I say, the low volume days simply don't register.
Conceptually:  The first method gets you an average Price (it literally computes the average of the price realized on each day).  The second method gets you "the average realized value of a unit of your product".  These will be comparable if the volumes from day to day are roughly constant, but not otherwise.
Comment: Never mind, figured it out.
Comment: How does Method 1 give you 3/2? What happened to the 1/50 it is multiplied by?
Comment: Are your comments out of sequence?  I expect you've worked it out, but just in case:  in my example I used $2$ observations, not $50$.  Easy to see what's going on with small data sets.
Comment: Thanks for replying so quickly. I just wasn't thinking clearly and asking questions before I thought them through.
Comment: Oh, no problem.  I note that the other commenter also proposed working with $2$ observations as a way to see things clearly.  Hard to hold $50$ observations in your head.

Need 2 calculations explained