Handle 500 error on form submit with JS or jQuery?

Question: I'm using a standard form/action to post to a restful web service, I'm trying not to use ajax due to the size and makeup of the form. Is there a way to attach error handling to the form submission? See my current code below.
<form   id="theForm"
        action="rest/url"
        method="post"
        enctype="multipart/form-data">
</form>

$("#theForm").submit(function(e){
    // Can anything be done to handle 500s here?
});

Here's the rest service.
@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(
    @FormDataParam("iD") Integer iD,
    ....
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail
    {
        // void to avoid redirect

        // exceptions return 500
        throw new ServerException(500);
    }

Comment: @Half_Duplex still nothing you can do, as the 500 error would be on another document entirely.
Comment: Note that if you're posting files, you won't be able to use jquery's serialize method.
Comment: If the form is being submitted normally, you can't handle the error with javascript.
Comment: _"I'm trying not to use ajax"_ No, I don't think you can handle any type of errors since you are submitting the form to another page
Comment: Unless, you submit the form to an iframe. Then, you can listen for the iframe load event and inspect it's contents to see if it is the error page or something else.
Comment: @Kevin B - What if I were to submit it myself using the jQuery submit() within my submit handler?
Comment: @KevinB Looks like I'll have to ajax and atry to serialize this form.
Comment: @Kevin B - used the FormData object and that takes care of the file input as well as the rest of the form.
Answer: Try this:
<form method="post" id="form>

</form>

Ajax code:
$('#form').submit(function () {
  $.ajax({
    url: 'your_url.html',
    data: 'some_data=somevalue',
    success: function (response) {
      // it was a success!
    }
    error: function () {
      // it was an error!
    }
  });
});

Please note you cannot handle the normal submission process! Only ajax requests can be checked by HTTP response. Simple form submit cannot be handled!
You can execute the above code on a submit button click!
Don't wanna use Ajax?
If you don't want to use ajax, then you need to use a server-side code. And check for the HTTP Resonse from the server! If it is 500, then redirect the user to another page! But remember, you cannot use jQuery to check the HttpResponseCode for the default submission process!
It is better if you start learning about web.config. That is the file where you manage the error and other customization of how server responds to the error and other conditions.
Comment: Thanks, but my goal was to replace ajax for this form with a creative alternative. I'm aware of how the config and server side work, I wrote the back end to return the 500. I don't want a redirect on any response, success or failure. I know I can suspend/divert form submission with jQuery, seems there should be a way to avoid the page refresh on the 500.
Answer: You can handle each type of Ajax error like that
$(function() {
$.ajaxSetup({
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});
});

Comment: I do not want to use ajax for this particular form, and also I'm already using ajaxSetup for the ajax that's happening everywhere else on the page.
Answer: After more reading, I found this was possible using a FormData object. This even takes care of the multiselect. Here's the code:
<form id="theForm">
    <input name="text" type="text">
    <select name="fileType">
    ...
    </select>
    <input name="file" type="file">
</form>

The jQuery
$("#theForm").submit(function(e){
    e.preventDefault();
    var theForm = new FormData($(this)[0]);
    $.ajax({
        url: '.../rest/save',
        type: 'POST',
        data: theForm,
        cache, false,
        contentType: false,
        processData: false
    });
    return false;
});

Jersey resource
@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(
    @FormDataParam("text") String text,
    ....
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail){
        log.info(fileDetail.getFileName());
        // exceptions return 500
        throw new ServerException(500);
    }


How can I redirect properly?

Question: Long story short I replaced an outdated site with a Drupal site at its previous url, let's say oldsite.org. But the old site was also accessed from oldsite.org/THIS, I think because it was a subdirectory of a larger site or something. But there are old links around that use oldsite.org/THIS and we want those to go to the homepage of the new site.
What is the proper Drupal way to do this redirect? I have thought of a handful of possible hacks, but I want to do it right.
Maybe a small module to handle the redirect. Or even htaccess somehow?
Answer: 301 redirects are considered the best way to handle redirected pages, for they inform search engines to update their databases with the new paths.
Edit your .htaccess file in a text editor. [Note: Be sure to save the file in "UTF-8" format.]
In the file, you will find the commands:
<code># Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # the rewrite rules are not working properly.
  #RewriteBase /drupal
RewriteBase /
</code>
Immediately after that code -- and before the Drupal-provided "Rewrite old-style URLs" commands -- add your rewrite rules using the following format:
<code>#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects
</code>
For detailed discussion https://drupal.org/node/38960
Answer: You can use Redirect module for this. You can set redirection path with status such as 301 etc..
For <code>.htaccess</code> redirect, you can take help from this documentation.

How can I redirect properly?


Getting the next node id for a Neo4j Node using the REST API

Question: EDIT
When i am talking about node and node id i am specifically talking about the Neo4j representation of a node not node as in Node.js

I am building out an application on top of Neo with node using the thingdom wrapper on top of the REST API and i am attempting to add my own custom id property that will be a hash of the id to be used in the URL for example.
What i am currently doing is creating the node and then once the id is returned hashing this and saving it back to the node, so in effect i am calling the REST API twice to create a single node.
This is a long shot but is there a way to get a reliable next id from Neo using the REST API so that i can do this all in one request.
If not does anyone know of a better approach to what i am doing?
Answer: The internal id of neo4j nodes is not supposed to be used for external interfaces, as noted in the documentation. That means especially it's not a good idea to try to guess the next id.
It's recommended to use application specific ids to reference nodes, if you use UUIDs (especially uuid type 4) there is only a minimal chance of collisions and you can compute them on node creation, before storing them in the database.
Comment: Hi Thomas thanks for the answer, the issue is uuid are not really what we are using, and we are using a simple hash of the id.  Your approach makes sense and was what we initial went with but like i said we now use a hash instead of the id.  The API is very early in creation and this may change again.
Comment: Then you will need the two calls, I think, as there is no sure way to tell what id you will get.
Answer: By curiosity, can I ask you why you need to have the Id stored in the Node?
But anyway, it's quite common in Node.js to call a succession of APIs. And you will see that with Neo4j it will be required more than once.
If you don't already use it, I can only suggest you to take a look at Async: https://github.com/caolan/async
And particularly to the "waterfall" method that allows you to call more than one API that use the result of the previous call.
Comment: Hi, to be honest the code is abstracted enough for it not to need an ASync library yet, the callbacks are limited and if its too deep its factored out.  I was simply looking for a way to not have to hit Neo twice.  The idea of having it stored in the db would mean i could pull it all out in one go as apposed to regenerating it each time, but it is something to look at.


Show select box only when checkbox is checked

Question: I use this code in order to show/hide select box depends if a checkbox is checked or not:
jQuery(document).ready(function($){
    $('[type="checkbox"][name="fields[special_proj_checkbox_field][]"]').change(function(){
      $('select.select').toggle(this.checked);
    });
});

This code is executed in the back-end, in the edit post screen.
It works well except for one thing -- the first time I get to the edit post screen, the checkbox isn't checked, but the select box is visible, only after I check the checkbox and unchecked it again, the box is hiding.
How can I make it hidden by default?
Comment: Can't you just add `display: none` or hide it in the beginning of the `document.ready` event callback?
Answer: You can initially hide the select
jQuery(document).ready(function($){
   var select = $('select.select').hide();
   //or select = $('select.select').toggle();
    $('[type="checkbox"][name="fields[special_proj_checkbox_field][]"]').change(function(){
      select.toggle(this.checked);
    });
});

Comment: if you save checkbox value to database and if it is checked/unchecked when post is loaded, you can do initial check:
`var select = $('.select), chk = $('[type="checkbox"][name="fields[special_proj_checkbox_field][]"]');`

`if (chk.is(':checked') select.hide();`

`chk.change(function(){select.toggle(this.checked);}`
Comment: By the way you there is no need to select checkbox with `[type="checkbox"]`. It's supposed that the name must be unique, so it's enough to do select only by the name. Depends of course of current situation ...
Comment: Now I have another problem, after I check the checkbox and save the post, the select box become hide again.. @pgk
Answer: As far as I know jQuerys .hide() function is triggering display:none. So you may initially add display:none to your box or add a $.hide() at the very beginning of your code.


$\int_{0}^{\pi }f(x+t)dt=\int_{0}^{\left [ n\pi \right ]}f(x+t)dt=0$

Question: Determine the continuous functions $f:\mathbb{R}\rightarrow \mathbb{R}$ so that:  $$\int_{0}^{\pi }f(x+t)dt=\int_{0}^{\lfloor n\pi  \rfloor }f(x+t)dt=0,\forall x\in \mathbb{R},n\in \mathbb{N}$$
All I've found is that $f = 0$ verifies.
Thank you!
Comment: In the integral limit, is $[\pi n]$ just a parenthesis, or does it denote the greatest integer (floor) function, or something else?
Comment: It's the floor function.
Comment: Do you know that the group of periods of a continuous function is closed?
Answer: If $f \colon \mathbb{R} \to \mathbb{R}$ is continuous, and $L > 0$ such that
$$F(x) := \int_0^L f(x+t)\,dt = \int_x^{x+L} f(t)\,dt\tag{$\ast$}$$
is constant, then $L$ is a period of $f$. That is easily seen by differentiating $(\ast)$,
$$0 = F'(x) = f(x+L) - f(x)$$
for all $x\in \mathbb{R}$.
Your condition thus implies that $\pi$ and $3$ (choosing $n = 1$) are periods of $f$.
Hence $S = \{ k\cdot 3 + m\cdot \pi : k,m \in \mathbb{Z}\}$ is contained in the set of periods of $f$. Since for a continuous function $g \colon \mathbb{R} \to \mathbb{R}$ the set
$$P(g) = \bigl\{ a \in \mathbb{R} : (\forall x\in \mathbb{R})\bigl(g(x+a) = g(x)\bigr)\bigr\}$$
of all periods of $g$ is closed, and $S \subset P(f)$ is dense in $\mathbb{R}$, it follows that $P(f) = \mathbb{R}$, i.e. $f$ is constant. With $\int_0^{\pi} f(t)\,dt = 0$ it then follows that $f\equiv 0$.
Comment: @CuriousKid7 Sorry, I too often forget that the $A \pm x$ notation for translates isn't universally known. $$f^{-1}(f(x)) - x = \{ y - x : y \in f^{-1}(f(x))\} = \{ y - x : f(y) = f(x)\}$$ It's the set $\{ a : f(x+a) = f(x)\}$.
Comment: How do we know that $P(g)$ is closed?
Comment: Depends on your favourite way to show that a set is closed. The complement is open: If $a \notin P(g)$, then there is an $x \in \mathbb{R}$ with $f(x) \neq f(x+a)$. By continuity of $b \mapsto f(x+b)$ there is $\varepsilon > 0$ with $f(x) \neq f(x+b)$ for all $b$ with $\lvert b-a\rvert < \varepsilon$, so $(a-\varepsilon, a+\varepsilon) \cap P(g) = \varnothing$. It is the intersection of a family of closed sets: For $x \in \mathbb{R}$ let $T(x) = \{ a \in \mathbb{R} : f(x+a) = f(x)\} = f^{-1}(f(x)) - x$. Then $P(g) = \bigcap_x T(x)$.
Comment: What do you mean by $f^{-1}(f(x)) - x$?
Comment: Ok, then it's the preimage of the closed set $f^{-1}(f(x))$ under addition by $x$, which is continuous. Sounds good.
Comment: Also, did you mean to say that $P(g)$ is the set of all periods of $f$?
Comment: @CuriousKid7 Oops, typo. Should be $g(x+a) = g(x)$ in that set definition. Fixing.


O que são os índices, B-tree, hash, GiST e GIN?

Question: No manual do PostgreSQL tem o seguinte trecho :

PostgreSQL provides the index methods B-tree, hash, GiST, and GIN.
  PostgreSQL fornece os métodos de índice B-tree, hash, GiST e GIN.

Mas afinal o que são estes métodos? e qual suas diferenças?
Answer: B-Tree
O B-tree, ou alguma variação dele, é o mais comum em todos os sistemas de banco de dados. Ele é muito eficiente para quase todos os casos comuns de uso. É uma árvore balanceada que permite todos os tipos de acesso (leitura, inserção remoção, em qualquer lugar) em tempo O(log n) (é um pouco mais complicado que isso, mas assim dá um ideia), que é muito rápido sempre, com volume muito grande ou muito pequeno de dados, mas importa mesmo quando é grande. É razoavelmente eficiente em espaço e mantém os dados ordenados, permitindo a leitura sequencial e de faixas eficientemente.
Hash
Nos casos onde não precisa da ordem ou da busca sequencial e as chaves são únicas (em que o programador garante isto, o índice não consegue), evitam colisão e possui grande volume de dados, o índice pode ser mais eficiente se usar uma função de cálculo de hash. Elas têm tempo O(1). Mas isso não quer dizer claramente mais rapidez. O tempo de cálculo da função pode ser maior que algumas iterações em uma árvore binária (e costumam haver poucas). Não costuma funcionar bem em disco ou outro armazenamento secundário.
A estrutura de hash ainda pode ter algumas dificuldades quando há colisões e buscas lineares (O(n)) são necessárias (ainda que raras, a não ser que as chaves não sejam únicas). Mas também pode-se "reclamar" de perda de tempo extra no B-tree quando necessita um rebalanceamento embora isto ocorra em circunstâncias mais específicas. Em todos os casos depende do algoritmo usado e o padrão de dados.
Existem casos, mas é raro, ter ganho expressivo por sua utilização. Pode haver ganhos em certos tipos de JOIN muito complexos. Só testando para ter certeza se vale a pena.
Ele não é crash-safe, nem é replicado, o que inviabiliza mais casos.
GIN
O GIN (Generalized Inverted Index) permite que uma chave possua vários valores, ou seja, que aponte para várias linhas na tabela de dados. Isto é importante quando a mesma chave pode estar presente em vários itens de dados. Em alguns casos ter um índice assim (B-tree permite isto também) pode ser mais eficiente em espaço e tempo de acesso. Não espere ganhos miraculosos.
Um bom uso é para busca de textos livres (indicar onde determinas palavras estão presentes.
Outro uso é quando um tipo de dados específico criado pelo usuário (programador) no banco tem uma característica de multiplicidade.
De uma certa forma podemos considerar um índice mais baixo nível. Algo quase interno.
GiST
O GiST (Generalized Search Tree) é uma forma mais abstrata, mais interna, onde podem ser implementadas várias metodologias de acesso. Ela é uma árvore balanceada, mas não possui muitas regras. Estas devem ser especificadas em um nível mais alto, provavelmente para algum tipo específico criado pelo usuário.
Conclusão
Em resumo, se não tiver um motivo muito forte, fique com o índice tradicional.
Coloquei no GitHub para referência futura.
Comment: O que seria *crash-safe*?
Comment: Se parar no meio não dá problema.


How is it possible to get a high $R^²$ & still have 'poor predictions'?

Question:
The insulin-sensitivity check index (QUICKI) has an excellent linear correlation with the glucose clamp index of insulin sensitivity (SI_Clamp) that is better than that of many other surrogate indexes. However, correlation between a surrogate and reference standard may improve as variability between subjects in a cohort increases (i.e., with an increased range of values). Correlation may be excellent even when prediction of reference values by the surrogate is poor.
Source:
Chen H, Sullivan G, Quon MJ. Assessing the predictive accuracy of QUICKI as a surrogate index for insulin sensitivity using a calibration model. Diabetes. 2005 Jul;54(7):1914-25.

Based on the above I am supposed to answer how it is possible to have a high correlation while at the same time having 'poor' prediction capacity, probably due to the increased range of values. The way I interpret this is a high $R^²$ or $r$ and 'relatively' wide prediction intervals. While I have previously seen this occur in a paper as well, I don't quite get it how it is possible when I look at the formulas:
$$R^² = \frac{SSR}{SST}\qquad {\rm or} \qquad1 - \frac{SSE}{SSTO}$$
And the variation that determines the width of the interval:
$$\newcommand{\mean}{{\rm mean}}S^²({\rm prediction}) = MSE \frac{1 + 1/n + (X_h - X_{\mean})^² }{\sum(X_i - X_{\mean})^²}$$
With $MSE$ is mean squared error, $X_h$ is the value of $X$ for which you want to set up a prediction interval, $X_{\mean}$ is mean of all $X$ values, $X_i$ is the value of $X$ in observation $i$. To my understanding, if we were to have the same sample size ($N$) but for a  wider range of $X$s, then your $R^²$ may increase as $SSR$ increases.
But at the same time, due to the wider range of $X$s the $S^²({\rm prediction})$ will also decrease as the denominator in the formula for $S^²({\rm prediction})$ gets bigger. Also, if $SSR$ increases while $SSTO$ remains the same, this also implies $SSE$ decreases.
Thus, am I right to say that this ($R^²$ high, predictions poor) can only occur when the $MSE$ remains unchanged and is relatively high, while $SSR$ and $SSTO$ increase (so that your $R^²$ increases)?
Or should I say: that the proportions of all elements in the $R^²$ formula (i.e.: $SSR, SSTO, SSE$) remain the same, but increase in absolute numbers. So that the MSE increases for the $S^²({\rm prediction})$, having less precise predictions, while $R^²$ remains high?
Comment: I wasn't aware I could edit it myself, it's been added.
Comment: For questions about quotes it's important to link or properly cite the origin of the quote, so that answerers can grasp the context before answering. I think the source is here: https://www.ncbi.nlm.nih.gov/pubmed/15983190
Comment: @Ferdi Will try to do so next time. I tried to show I already put some thought in it, before immediatly posting the question here :) Btw, I notice a small mistake in the edit of the formula of S². It should be: MSE [ 1 + 1/n + (Xh - Xmean)² / sum (Xi - Xmean) ]   Now 1 + 1/n is part of the nominator
Comment: Hint: consider a dataset exhibiting excellent correlation.  Introduce one more subject whose $X$ value is outlying.  Consider what happens to the least-squares fit as well as $R^2$ as you vary the $Y$ value for this subject.
Comment: Did you check this site for possible duplicate questions?
Comment: My bad about the quote, I had it quoted from an exam example question but should have looked up the article on the internet. Also thanks for editing @Ferdi. I did check for similar questions on this website, but wasn't successful.
Comment: @KaspervanEck, good question. In General shorter questions are more likely to receive (good) answers, because users are prone to read less. Try to come straightly to the point when asking your next question.
Comment: Also consider just-determined problems. You get high $R^2$ but no guarantee of good fitting.
Comment: @mkt it'd be the other way around, if it's the case. This question was asked over 2 years ago, the one you answered was asked only yesterday.
Comment: I see, wasn't aware. Then it'd make sense to reformulate the short definition of a duplicate:
This question has been asked before and already has an answer.
Comment: @Amonet I agree, it is confusing. I appreciate this question & answer, though. +1!
Answer: As you state, $R^2 = 1-SSE/SST$, where SSE is the sum of squared residuals of the model and SST is the sum of squared residuals of a simple model that just predicts the average response variable for each observation.
Consider two regression models. The first has data in a relatively small range:
dat <- data.frame(x=1:10, y=c(2, 1, 4, 3, 6, 5, 8, 7, 10, 9))
plot(dat)

We get an $R^2$ of 0.88, with SSE = 9.7 and SST = 82.5.
Now add the point with x=100, y=100 and re-run the experiment:
dat2 <- data.frame(x=c(1:10, 100), y=c(2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 100))
plot(dat2)

The second model has $R^2$ of 0.999, with SSE = 10.0 and SST = 8201. The model fit hasn't really improved (both models have a RMSE of roughly 1). However, the $R^2$ has improved dramatically because the simple baseline driving SST is much worse in the second case. Instead of predicting the sensible value of 5.5 for all observations as it did in the first case, it is now predicting 14.1.
We now see that "wide data" (aka a large range of response variables) can cause SST to become much worse than the "narrow data" case, causing the $R^2$ to improve without a closer model fit.
Comment: Just to note, there *many* reasons why predictions may be poor despite high $R^2$ value. For example, I would be very skeptical about predictions from a model with $R^2 = 1$. I do believe @josliber's answer here provided correct reasoning for why high $R^2$ values may not mean a better surrogate in this particular case presented by the OP.
Answer: If variability between subjects increases then variability within subjects decreases, i.e. the intraindividual measurement error is greater. For instance, with insulin resistance we often use HOMA-IR which is a great marker because it only requires one measure of fasting glucose/insulin over time... but if you measured the same individual tomorrow, you would have a different prediction, like with blood pressure, protein urea, etc. Clinically, we rely on multiple measurements of imprecise markers to make decisions. If you predict a highly variable marker within an individual well, it still won't tell you much about that individual in general.


how to write findOneAndUpdate query in express.js?

Question: i have shown  my data , which is stored in database like this
<code>{
    "_id": {
        "$oid": "5799995943d643600fabd6b7"
    },
    "Username": "xx",
    "Email": "email@example.com",
    "Info": "Deactivate",
    "Description": "aajdjdjddjdkjddjdjdhdj",
    "VerificationCode": "594565",
    "VerificationExpires": {
        "$date": "2016-10-07T10:20:20.077Z"
    }

}
</code>
My controller:
if Username, Email, Info are matched I need to update " Info = 'Active' " this is working at the same time i need to delete 'VerificationCode' field and 'VerificationExpires' field how can i achieve this?
<code>exports.updatearticle = function(req, res) {
    Article.findOneAndUpdate(
        { "Username":'xx', "Email":'firstname.lastname@example.com', "Info": "Deactivate" },
        { "$set": { "Info": "Active" } },
        { "new": true }
        function (err, doc) {
            if (err) { // err: any errors that occurred
                console.log(err);
            } else { // doc: the document before updates are applied if `new: false`
                console.log(doc); // , the document returned after updates if `new  true`
                console.log(doc.Info);
            }

        }
    );
};
</code>
above condtion matched and info getting changed but i want to delete VerificationCode,VerificationExpires some one help me out
Answer: <code>    exports.updatearticle = function(req, res) {
    Article.findOne( { "Username":'xx', "Email":'firstname.lastname@example.com', "Info": "Deactivate" }, function(err, result){
       if (!err && result) {
        result.Info = "Active"; // update ur values goes here
        result.VerificationCode = "";
        result.VerificationExpires = {};
        var article = new Article(result);
        article.save(function(err, result2){
            if(!err) {
               res.send(result2);
            } else res.send(err);
        })

       } else res.send(err);
    });
  }

 home this may help
</code>
Comment: getting error F:\app\test\node_modules\mongoose\lib\utils.js:413
        throw err;
        ^

Error: Can't set headers after they are sent.
Comment: in ur function there may be two time res.send() is executing, once u sent res.send() then dnt run any other codes, share me ur code once again
Comment: sorry, i was missing one else, i have added, now u can use it
Comment: findOneAndUpdate function and what i have given both will work same manner, so you can use whatever i shared,  bcz u cnt modify based on my ans, findOneAndUpdate and findOne function has differennt syntax


RhinoMock says: "Type doesn't match the return type"

Question: I've written such class:
public class A
{
    public virtual int LowLimit { get; set; }

    internal virtual bool CheckLimit(int measurement)
    {
        return LowLimit <= measurement;
    }
}

And a test for it:
MockRepository mocks = new MockRepository();
var limit = mocks.StrictMock();

Expect.Call(limit.CheckLimit(2)).Return(true).Repeat.Once();
mocks.ReplayAll();
limit.CheckLimit(2);
mocks.VerifyAll();

And it fails with:
System.InvalidOperationException : Type 'System.Boolean' doesn't match the return type 'System.Int32' for method 'A.get_LowLimit();'
But when I replace internal keyword for CheckLimit method to public, it works ok.
Why it is behaiving like that?
Answer: If you're using an external library (StrictMock), then it can't access any of your internal methods.
It looks like the StrictMock implementation is trying to use A's CheckLimit, but because it can't find an implementation probably uses its own implementation which uses A's LowLimit.
Comment: Strange. If it can't access CheckLimit, how does it know that CheckLimit uses LowLimit inside? And what is the solution? I need to have internal keywork there :(
Comment: Ah, anyway I got it, so thanks. I've added [assembly: InternalsVisibleTo(Rhino.Mocks.RhinoMocks.NormalName)] to my assably and it worked. Thanks


Query geo distance on elasticsearch with dynamic distance

Question: I am facing an issue with Elasticsearch.
I would like use the geo distance feature to fetch all the item located N km maximum from a given localization.
Here is my DB schema:
{
    "user_id": "abcde",
    "pin" : {
       "location" : {
           "lat" : 40.12,
           "lon" : -71.34
        }
    },
    "is_active": true,
    "action_zone": 50
}

I have this query which works pretty well:
{
    "query": {
        "bool" : {
            "must" :
                [{
                    "term": {
                        "is_active": True
                    }
                }],
            "filter" : {
                "geo_distance" : {
                    "distance" : "200km",
                    "pin.location" : {
                        "lat" : 40,
                        "lon" : -70
                    }
                }
            }
        }
    }
}

Now, I would like to modify this query a bit to replace dynamically the distance (200km in my example) by the value "action_zone" of each item of in the DB.
That would be great if someone could help me. :)
Answer: I found the solution using a script :D Thanks anyway !
{
"query": {
    "bool" : {
        "must" :
            [{
                "term": {
                    "is_active": True
                }
            },{
                "script" : {
                    "script" : {
                        "params": {
                            "lat": 40.8,
                            "lon": -70.1
                        },
                        "source": "doc['location'].arcDistance(params.lat, params.lon) / 1000 < doc['action_zone'].value",
                        "lang": "painless"
                    }
                }
            }]
        }
    }
}

}
Doc: https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-script-query.html
Answer: Unfortunately, the geo_distance query doesn't allow to use scripting in order to specify a dynamic distance. What you could do, however, would be to use a terms aggregation on the action_zone field so as to bucket all your documents within a specific action zone.
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "is_active": True
          }
        }
      ],
      "filter": {
        "geo_distance": {
          "distance": "200km",
          "pin.location": {
            "lat": 40,
            "lon": -70
          }
        }
      }
    }
  },
  "aggs": {
    "zones": {
      "terms": {
        "field": "action_zone"
      }
    }
  }
}

Otherwise, you could also use a range aggregation on the action_zone field with a few specific distances:
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "is_active": "True"
          }
        }
      ],
      "filter": {
        "geo_distance": {
          "distance": "200km",
          "pin.location": {
            "lat": 40,
            "lon": -70
          }
        }
      }
    }
  },
  "aggs": {
    "zones": {
      "range": {
        "field": "action_zone",
        "ranges": [
          {
            "to": 50
          },
          {
            "from": 50,
            "to": 100
          },
          {
            "from": 100,
            "to": 150
          },
          {
            "from": 150
          }
        ]
      }
    }
  }
}


OpenGL: Lighting without shaders

Question: How can I make phong lighting without using a shader (university task).
Can I manually calculate ambient, diffuse, specular and transfer their sum to glColor?
UPD:
I have a good display of the sum from ambient and diffuse. But the specular doesn't render correctly, it gets very scattered.
My problem in picture:

My code:
<code>void GLRenderSystem::renderTriangleSoup(const std::vector<Vertex>& vertices)
{
    glBegin(GL_TRIANGLES);
    for (const auto& vertex : vertices)
    {

        glm::vec3 norm = glm::normalize(glm::vec3(glm::mat3(glm::transpose(inverse(model))) * vertex.normal));
        glm::vec3 FragPos = view * model * glm::vec4(vertex.position, 1.0f);
        glm::vec3 viewDir = glm::normalize(viewPos - FragPos);
        glm::vec3 result = glm::vec3(0.0f);

        for (const auto& light : lightList)
        {
            if (light.isEnable)
            {
                // ambient
                glm::vec3 ambient = (Ka * light.Ia) * vertex.color;

                //diffuse
                glm::vec3 lightDir = glm::normalize(light.position - FragPos);
                float dist = glm::length(light.position - FragPos);
                float diff = glm::max(glm::dot(norm, lightDir), 0.0f);
                float Att = 1.0f / (1.0f + (0.01 * pow(dist, 2)));
                glm::vec3 diffuse = (Kd * light.Id) * (diff * vertex.color);

                //reflect
                glm::vec3 reflectDir = glm::reflect(-lightDir, norm);
                float spec = glm::pow(glm::max(glm::dot(viewDir, reflectDir), 0.0f), Se);
                glm::vec3 specular = (Ks * light.Is) * (spec * vertex.color);

                // result color
                result += (ambient + diffuse + specular);
            }
        }

        glColor3fv((GLfloat*)&result);

        glm::vec4 vr = proj * view * model * glm::vec4(vertex.position, 1.0f);
        glVertex3fv((GLfloat*)&glm::vec3(vr.x / vr.w, vr.y / vr.w, vr.z / vr.w));
        glNormal3fv((GLfloat*)&vertex.normal);
    }
    glEnd();
}
</code>
Comment: I get the impression that you either misunderstood the assignment, or left out important parts of it in this question. There are several possible ways to achieve the desired output image "without shaders", but the role opengl has to play in the solution is totally unclear. I.e. it would really help to know what you _should_ use, instead of knowing what you should not use. After all, you can do all software rendering, and it would fulfill the requirement as currently stated.
Answer: (Original question was: can I produce specular highlights without using glMaterial or shaders)
No.
Take the example of a large triangle where the corners are only lit by diffuse light and you want a specular highlight in the middle.
The lighting equation at the corners does not have a (significant) specular contribution, so you can only pass the diffuse color as glColor.
OpenGL will simply linearly interpolate the color between the three corners; it will not magically generate a specular highlight in the middle, unless you a) use glMaterial to tell it how fragments should interact with the lighting setup, or b) write a fragment shader to evaluate the lighting equation for each fragment.
In 2020, just use shaders.
Comment: "(Original question was: can I produce specular highlights without using glMaterial or shaders) No." That's not stricly true. One can still increase the tesselation so that triangle size approaches a single pixel in area. Or one could calculate the shading on the CPU and apply it as texture. Note that for all practical purposes, I agree to your answer, I'm just nitpicking here...
Comment: Your assignment is asking for something that is impossible, so either you misunderstood it or the assignment is bogus.
Comment: I have nothing against shaders, they just asked me such a task at the university
Comment: then can you help me how to do this task using glMaterial, please
Comment: Ask a new question showing what you tried, with actual code.
Comment: Botje, I revised my post and now I wrote what I really need
Comment: Suggest you read your course material on the `glLight` and `glMaterial` calls and/or read [some tutorial on them](https://www.glprogramming.com/red/chapter05.html) I have not used the legacy API in 8 years so could not possibly help you with that.

OpenGL: Lighting without shaders


Converter função for next ASP para PHP

Question: Tenho esta função em ASP e preciso converter para PHP
DADOS:
cod = "01A" ou cod = "01B" ou cod = "01C"

titulo = "Novidade"

FUNÇÃO:
letra = right(cod,1)
str = array("A","B","C")
for i = lBound(str) to ubound(str)
if (instr(1,letra,str(i),vbtextcompare) <> 0) then
    titulo = titulo & "-" & i+2
end if
next

RESULTADO:
se cod="01A" então titulo = "Novidade-1"

se cod="01B" então titulo = "Novidade-2"

se cod="01C" então titulo = "Novidade-3"

Agradeço a todos pela ajuda
Answer: Como o objetivo é comparar o valor de letra com o item atual do array str(i).
Uma forma de fazer isso com php é criar um gabarito atra´ves de um array onde as chaves são as letras(A-Z) e os valores são de 1-26 quem realizada essa tarefa é array_merge() que recebe dois argumentos o primeiros são as chaves do novo array e o segundo os valores. Depois disso basta verificar se existe o indice $letra em $str caso positivo escreve novidade- seguido do valor.
$arr = array('01A', '01B', '01C', '01Z');
$titulo = 'novidade';
$str =  array_combine(range('A', 'Z'), range(1,26));

foreach($arr as $v){
    $letra = substr($v, -1, 1);
    if(isset($str[$letra])){
        echo 'novidade-'.$str[$letra] .'
';
    }
}

Saida:
novidade-1
novidade-2
novidade-3
novidade-26

Comment: rray, agradeço, informo mais detalhes: O array contém só letras (alfabeto completo de A a Z). Os COD são nnA (2 nºs e 1 letra). A função compara a letra do COD e incrementa no título o '-1' se for letra A; '-2' se for letra B assim por diante. Espero ter esclarecido, qq dúvida post. Obrigado.
Comment: Esqueci de informar o mais importante. Antes da função tem; letra=right(cod,1) aqui é separada a letra do cod para a função comparar. desculpe a falha.
Comment: @Geo então vc compara apenas se as letras são iguais e aí faz o incremento?
Comment: isto mesmo. por exemplo COD=23B o titulo fica = novidade-2
Comment: @Geo editei a resposta veja se agora está correta.
Answer: Olha o que eu entendi da pergunta, você quer que a letra corresponda a um index? Se for isso veja se essa solução te atende:
 <?php
  $letras = range('A', 'Z');
  $cod = '10F';
  $titulo = "Novidade";

  $letra = substr($cod,-1);
  $index = array_search($letra, $letras)+1;

  print "$titulo-$index\n";

Ta certo que eu extrapolei um pouquinho do seu resultado, mas o resultado final seria esse:
Novidade-6

Comment: quase. O cod é uma variável única. Exemplo: Chegou uma variável $cod='10F'. Então separa a letra F compara e acrescenta -6 no titulo. A função checa só um cod. de cada vez. E o resultado é único: cod=10F terá novidade-6. Obrigado
Comment: kkkkkkkkkkkkk, entendi... mas isso é mais fácil... é a gnt responde mais abrangente, pra contemplar tudo... mas é só retirar do array
Comment: Flavio fiz assim e funcionou: $arr = array($cod); Coloquei a variável única dentro do arr(array). Mas dá para reduzir mais? O meu raciocínio é antigo, Com 70 anos e 50 de linguagens ultrapassadas. Agora que estou convertendo asp em php. Conto com a compreensão dos colegas. Obrigado
Comment: Flávio e rray, agradeço imensamente as rápidas respostas. As 2 sugestões funcionaram perfeitamente. Vou aproveitar as 2 tb para outras funções. Muito Obrigado pela atenção!!!
Comment: Tentei ticar as 2 respostas, mas só aceita 1. Rray agradeço por dedicar seu tempo e conhecimento. Boa Sorte a todos.
Comment: @Geo o importante é sempre continuar a aprender, boa sorte. A comunidade ta aqui sempre pra te ajudar a crescer.

Converter função for next ASP para PHP


How to estimate statistical significance of the difference between two groups

Question: I need to be sure that the difference between estimations of the percent of returning visitors to a web page in two groups is not just a random difference. I have the following data:
<code>       Group 1     Group 2
Day 1  2.0%        2.2%
Day 2  1.8%        2.1%
...
Day 5  2.1%        1.5%
</code>
For example, there is 2.0% of persons who have returned to a web-site on Day 1 (which means that a person visited the website more than 1 time during the day).
How can I evaluate the statistical significance of the difference between Group 1 and Group 2? Do I need more that 5 days of observations, or can I extract some conclusions based on these 5 days?
The size of Group 1 and Group 2 is 10000 and 12000, respectively.
Answer: First you need to test if your model matches the parameters of a t-test, if so, the easy way is to go for a T-Test against the null hypotheses of both distributions being the same.
If your populations do not match the parameters of normalit`y and homocedasticity (similar variances between both datasets) you will have to go for a non-parametric alternative, here you have an even higher number of options, Wilcoxon's test, or Friedman's are quite standard and generally, well accepted in the academic community.
You can extract some conclussions with only 5 samples? Sure you can, but you have to question yourself if the sample is representative for your problem, probably for a problem involving active users, a 5-day scope is a little limited, consider using a bigger scope


Spring MVC + Hibernate with bidirectional relationship

Question: I've been working with RESTful service built by Spring MVC + Hibernate + MySQL.
In the database, I have two tables - topic and comment. ID column of topic table is the foreign key of the comment table. I generate the models and DAOs using Hibernate Tools:
Topic model:
...

@OneToMany(fetch = FetchType.LAZY, mappedBy = "topic")
public Set<Comment> getComments() {
    return this.comments;
}

...

Comment model:
...

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "topic_id", nullable = false)
public Topic getTopic() {
    return this.topic;
}

...

Here comes the question. I can get the detached topic object DT using findById(). However, every time I want to send DT as the response body to the frontend, 'no session' exception is thrown because LAZY object - comments, can only be accessed within the session.
1) if I don't change to EAGER, my solution is to create new Topic object NT and retrieve values (except comments) from the DT. Then return NT as the response body. Is this the best practice?
2) if I change the @OneToMany part to EAGER, the problem is still unsolved. Because when I send DT, set of comments are included, and every comment has relationship to topic as declared by @ManyToOne. So still 'no session' exception is thrown.
3) if I change both @OneToMany and @ManyToOne to EAGER, computer will stuck as it will go from topic to comment and back to topic, iteratively, never stop.
So, how you guys suggest to return topic as response body.
Comment: Creating a View Object or a DTO (Data Transfer Object) to return information to the front end is not unusual or bad practice. You can get rid of the 'no session' by setting the comments of the Topic to null or reinitializing to an empty array. I'm not sure you need the ManyToOne bidirectional relationship annotation in the comment model. The fact the you have a list of comments in the topic and have it annotated there should be sufficient.
Comment: Checkout [jackson-datatype-hibernate](https://github.com/FasterXML/jackson-datatype-hibernate) to work with lazy-loading aspects
Comment: For handling cyclic object graphs see [JsonIdentityInfo](http://wiki.fasterxml.com/JacksonFeatureObjectIdentity)
Comment: I don't understand why `Topic` is fully mapped in `Comment`. It makes no sense, if you regard `Topic` as an aggregate. So what's the use case? Including it in the response is like a webpage about a car that contains all information about its manufacturer.
Comment: @zeroflagL Maybe I misunderstand something. Does foreign key must come with a `@OneToMany` or `@ManyToOne` relationship? Is it good practice to have foreign key without any relationship?
Comment: Possible use case: You have a list of topics and load all comments for one topic. With your solution you would load the topic again and do that for every comment. What is the purpose of a comment knowing about the topic? Do you ever load a comment without already having a topic? Would you ever load comment no. 12345 and then ask yourself "What topic does that comment belong to"? I don't think so. As far as I can see it the comment does not need a reference to the topic.
Answer: After long time of research, I finally have acceptable solution.
But first thing first, the reason of using bidirectional relationship can be found here.
My solution is using jackson-datatype-hibernate, which thanks to @ZeeMesi. Here's the steps:
Step 1: dependency
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-hibernate4</artifactId>
        <version>2.6.4</version>
    </dependency>

Step 2: spring context
<mvc:annotation-driven>
    <mvc:message-converters>

        <beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <beans:property name="objectMapper">
                <beans:bean class="com.hersbitcloud.cancercloud.HibernateAwareObjectMapper" />
            </beans:property>
        </beans:bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Step 3: create new class
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
    Hibernate4Module hm = new Hibernate4Module();
    registerModule(hm);
}

Then all the lazily fetched object will be null.


Is the pitch-producing mechanism for singing and humming the same or entirely different?

Question: The sound-producing mechanisms in string instruments and the flute are entirely different. Are the pitch-producing mechanisms used while singing a song and humming a song (humming with closed lips and no tongue movement) the same, or entirely different?
Answer: You can try this for yourself. Sing a note, to any vowel sound (try them all) and whilst doing so, close your lips. Now you're humming that same note. Feel any difference? Probably not, because the note itself is made further back. Somewhat like putting a mute on a trumpet bell, or covering a loudspeaker with something. All you're doing is muting the sound by closing the lips and humming.
So, for Stinkfoot in particular - the answer to 'Is the pitch-producing mechanism for singing and humming the same or entirely different?' is actually 'No' , with the caveat that it's pretty damned close rather than entirely different, at least as far as the layman's concerned. Go (a lot deeper) and it's not exactly the same, but for all intents and purposes says 'yes'.
Comment: I think this is incomplete. To be fair, so is the OP's question, but while the fundamental pitch depends only on the vocal cords, the overtones and whatnot depend on the complete shape of the acoustic cavity, the vocal cord waveform (which tends to be amplitude-dependent), and so on.
Comment: Also, the ability to hit different pitches can be affected by the shape of the mouth, because with the mouth and pharynx relaxed and wide enough, the two act like the bell of a brass instrument and create a more gradual change in mechanical impedance, which can shorten the resonant column in the lungs and pharynx and push the highest possible note up slightly. So it can get pretty complicated, but the basics are that it's mainly the vocal cords either way.
Answer: As Tim suggested, here is some additional information.  His answer, by the way, is (sorry in advance) pitch-perfect.
While the fundamental pitch depends only on the vocal cords, the overtones and whatnot depend on the complete shape of the acoustic cavity, the vocal cord waveform (which tends to be amplitude-dependent), and so on.  To clarify a little- the throat, mouth, and nasal cavities will produce various harmonics as well as phase-shifted copies of the original sound.  The vocal cords, I believe, do not vibrate as perfect sine waves, and further the waveform will change with amplitude, thus changing the overtone series at the origin.


Create setup using installshield for particular computer domain only

Question: I am working on window application. I am using installshield to create setup for this application. Till then everything is working fine i am able to install setup on any machine.
Problem:
For security reason i want to restrict my setup for particular domain only i.e suppose in my organization we are using aaa.com domain then this setup will only able to execute on this domain.
Please let me know if you need more information.
Comment: ok, I am looking into your answer and let you know if it will work..
Comment: Could you possibly check domain in the registry before you installation?
Answer: This is one of the options you can take.
To get the domain name from registry would do the job for you.
I have not used InstallShield to that extent but I have found this link that explains the method.
For the reference I am posting the code from said website here:
Public blnResult
Public strDomain
Public strFQDomain
Public objRootDSE

blnResult = BindToAD
If Not blnResult Then
WScript.Quit(False)
End If

Function BindToAD()
Dim blnResult_Bind

BindToAD = False

On Error Resume Next
Set objRootDSE = GetObject("LDAP://RootDSE")
If (Err.Number <> 0) Then
Exit Function
End If

strDomain = objRootDSE.Get("DefaultNamingContext")
If (Err.Number <> 0) Then
Exit Function
End If

'// Shouldn't ever be true if no error was returned, but...
If Len(strDomain) = 0 Then
Exit Function
End If

blnResult_Bind = GetFQDNFromNamingContext(strDomain, strFQDomain)
If blnResult_Bind Then
BindToAD = True
Else
If (Err.Number <> 0) Then
Exit Function
End If
End If

On Error Goto 0
End Function

'// ---------------------------------------------------------------------------------
'// GetFQDNFromNamingContext
'// Purpose: Converts a Naming Context into a DNS name
'// Input: strNamingContext e.g. DC=Domain,DC=Company,DC=com
'// Output: FQDN for strNamingContext e.g. Domain.Company.com
'// Returns: True/False
'//
'// Notes: LDAP allows for commas in strings, as long as they are escaped with a \ character.
'// e.g. "CN=Lewis\, Chris"
'// Since commas are not allowed in domain names, there is no parsing for them here.
'// ---------------------------------------------------------------------------------
Function GetFQDNFromNamingContext(ByVal strNamingContext, ByRef strFQDN)
Dim arrDomain
Dim intCount
Dim strTemp

GetFQDNFromNamingContext = False

'// Parse the NC by creating an array with the comma as an array boundry
arrDomain = Split(strNamingContext, ",")

For intCount = 0 To UBound(arrDomain)
'// Add a "." if needed
If Len(strTemp) > 0 Then
strTemp = strTemp & "."
End If

'// Remove the "DC=" and add this item to the temp string
strTemp = strTemp & Mid(arrDomain(intCount), 4)
Next

strTemp = Replace(strNamingContext,"DC=","")
strTemp = Replace(strTemp,",",".")

'// Return the FQDN
GetFQDNFromNamingContext = True
strFQDN = strTemp
End Function

Answer: Basically you need to get the domain name early in the setup with a custom action, set a property and then use that property in a launch condition. This has several answers about getting the current domain name:
Get the domain name of a computer from Windows API
However this is the kind of test that often works better in the application. An install-time test means that the user cannot install and then join the domain and run the app. It also means the user can join the domain, install the app, and then leave the domain (maybe even take a laptop home) and continue to run the app. So what is the "security reason" you mention? if domain membership is a requirement of the application then add a run time check to the application and let the install happen anywhere.
Comment: Thanks @PhilDW for your reply. So what will be the best way to make a setup secure means only authorized member can install or use. Always welcome to your valuable advice and suggestions.
Comment: My suggestion is to put the domain check in the app for the reasons I mentioned, and the link shows the kind of code to use.


Show that if $u_n + u_{n+1} \sim \dfrac{1}{n}$ then $u_n \to 0$

Question: Saw this question in my textbook : Let $(u_n)$ be a real decreasing sequence such that :
$$u_n + u_{n+1} \sim \dfrac{1}{n}$$
Show that $(u_n)$ converges to $0^{+}$ and give a simple sequence equivalent to $(u_n)$
My attempt : for every $\epsilon > 0$, we have for every $n\ge N $ :$$2u_n < u_n + u_{n+1} \le |u_n +u_{n+1}|\le \epsilon$$
It seems like I need to show that the terms of this sequence are all positive for this to work, I just don't know how to procede.
Comment: If it is decreasing, the first inequality is wrong
Answer: $(u_n) $ is decreasing, so to prove it converges, you just need to show that
$$(\exists m\in\Bbb R)\;: (\forall n\in\Bbb N)\; u_n\ge m$$
Assume that
$$(\forall m\in \Bbb R)\;(\exists N\in\Bbb N) \;:\; u_N<m$$
then
$$(\forall n\ge N)\; u_n\le u_N<m$$
and with $m=-1$,
$$(\forall n\ge N)\; u_n+u_{n+1}<-2$$
thus $$\lim_{n\to+\infty}(u_n+u_{n+1})\ne 0$$
but
$$u_n+u_{n+1}\sim \frac 1n$$
Finally, if we put $$\lim u_n=L$$
we will have
$$L+L=0\; and\; L=0^+$$
Answer: Suppose that there exists $n_0$ such that $u_{n_0}<0$, this implies that for every $n>n_0, u_n\leq u_{n_0}$, we deduce that if  $n>n_0, |u_n+u_{n+1}|>2|u_{n_0}|$. Take $N$ such that $N>n_0$ and ${1\over N}\leq {{u_{n_0}}\over 4}$. For $n>N$,
$|u_n+u_{n+1}-{1\over n}|\geq 2|u_{n_0}|-{1\over n}\geq 2|u_{n_0}|-{{u_{n_0}}\over 4}={3\over 4}u_{n_0}$. Contradiction.
Since the sequence it positive and decreasing, it as a limit $l$, and $lim(u_n+u_{n+1})=2l=lim {1\over n}=0$ implies that $l=0$.
Answer: Your intuition on non-negativeness of the terms of $u_n$ is correct, since if $u_{n_0}<0$ for some $n_0$ then
$$
u_n+u_{n+1}<2u_{n_0}\implies u_n+u_{n+1} \not\sim{1\over n}\quad,\quad n>n_0
$$


Instalação do Atom Text Editor

Question: Descobri um novo editor de código há pouco tempo, o Atom, que está na plataforma GitHub. A minha dúvida prende-se com a instalação deste editor e quanto à documentação que dão. Tenho que instalar o Node.js ou simplesmente descarregar o Atom e instalar?
P.S: Não tenho muitos conhecimentos de GitHub.
Answer: Os dois. O node.js se faz necessario para que o Atom seja executado corretamente.

Instalação do Atom Text Editor


Saber a cor do Button Android Studio (Java)

Question: Boa tarde, preciso saber ler a cor do Button e armazenar em uma váriavel no java para plataforma Android porém está apresentando erros, podem me ajudar ? Segue abaixo meu código:
private EditText cor;
public Button coreshexa;

coreshexa = (Button) findViewById( R.id.btn1);
cor = (EditText) findViewById( R.id.txtviewcorcateg);
ColorDrawable buttonColor = (ColorDrawable) coreshexa.getBackground();
cor.setText((CharSequence) buttonColor);

Comment: Qual erro que tá dando? e passe mais informações do código, vc tá inicializando as variáveis em qual método?
Comment: Quando clico no botão para ler o background do botão ele diz que a aplicação parou, apenas esse comando está apresentando erro na aplicação, a ideia é fazer uma paleta de cores com botões e ler o hexadecimal do botão escolhido
Comment: Ola Matheus, conseguiu resolver pela minha resposta?
Answer: pelo seu exemplo faça o seguinte:
ColorDrawable buttonColor = (ColorDrawable) coreshexa.getBackground();

//recupera a cor do botão como inteiro
int colorInt = buttonColor.getColor();

//transforma o inteiro da cor em hexadecimal
String colorHex = Integer.toHexString(colorInt);

cor.setText(colorHex);

Caso queira utilizar a cor do botão em outro botão:
//se for usar em Hex:
coreshexa.setBackgroundColor(Color.parseColor("#"+colorHex));
//se for usar em int:
coreshexa.setBackgroundColor(colorInt);

Comment: @MatheusRibeiro, Se a resposta te ajudou, por favor marque-a como respondida e/ou como útil.
Comment: Muito obrigado Murilo, desculpe a demora para dar um retorno mas seu código meu ajudou muito, agradeço pela ajuda.


How do I run multiple cron jobs?

Question: I want to run 4 cron jobs inside Drupal, in four different times.
How can I achieve that? Is there any module for that?
Answer: Try out the Ultimate Cron module.

Runs cron jobs individually in parallel using configurable rules, pool management and load balancing. Multiple rules per cron job. Configuration per job (enable/disable, rules, etc.)

There is also the Elysia Cron module.

Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.
Comment: @Lasitha Note that to allow Elysia cron to initiate Cron Jobs at four different times, you need to have crontab scheduled for every minute. http://drupal.stackexchange.com/a/37929/790
Answer: Elysia Cron is the module you are looking for.

Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

How do I run multiple cron jobs?


Ubuntu 12.10 virtualhost conflict

Question: I have 2 sites on my server. One I access via my IP, x.x.x.x/site1. The other is a registered domain name, www.mysite.com.
Initially, I had only my /etc/apache/sites-available/default file available but when I tried loading either of the sites above I just got my /var/www/index.html output.
I included a new virtualhost for mysite.com with the following code:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/mysite
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /var/www/mysite>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Mysite.com only loads when default is disabled but then, x.x.x.x/site1 doesn't.
So, I enable the default virtualhost which has the following code:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Now, x.x.x.x/site1 works but mysite.com does not - instead it loads the /var/www/index.html page.
I'm confused about what the issue is. I would appreciate some help.
Answer: In order for a virtual domain to work it needs to know what host to map to. In your http request for the browser it sets a Host header like
Host: mysite.com

So apache will read that to figure out what vhost entry to use. You need to add something like
ServerName mysite.com www.mysite.com

To the mysite.com virtual host in the <VirtualHost *:80>

Ubuntu 12.10 virtualhost conflict


How to do multiple conditions for db_update by using OR condition?

Question: I would like to convert the following UpdateQuery statement to work with multiple conditions by using OR instead of the default AND condition.
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition('name', 'seven') // OR
  ->condition('name', 'rubik')
  ->execute();

Is it possible?
Answer: Drupal 7
Yes, it is possible by using db_or() as in the following example.
db_update('system')
  ->fields(array('status' => 1))
  ->condition('type', 'theme')
  ->condition(db_or()
    ->condition('name', 'seven')
    ->condition('name', 'rubik')
  )
  ->execute();

For db_select(), see the answers given in  "OR" condition in db_select() and Nested OR and AND condition with db_select.
Drupal 8
You can still use db_or() as in Drupal 7, but it's deprecated in Drupal 8.0.x and removed in Drupal 9.0.0. Instead, a \Drupal\Core\Database\Query\Condition object should be created as in the following code, taken from BooleanOperator::queryOpBoolean().
if ($this->accept_null) {
  if ($query_operator === self::EQUAL) {
    $condition = (new Condition('OR'))
      ->condition($field, 0, $query_operator)
      ->isNull($field);
  }
  else {
    $condition = (new Condition('AND'))
      ->condition($field, 0, $query_operator)
      ->isNotNull($field);
  }
  $this->query->addWhere($this->options['group'], $condition);
}


Let Emacs move the cursor off-screen

Question: Is it possible to let Emacs have the cursor be moved off-screen, like most GUI text editors work? This is one of the biggest things that bothers me when I use Emacs over any GUI editor. When I scroll down, the cursor is "pushed forward" by the top of the buffer.
I had previously thought that this was completely impossible, because this is hard-wired into the architecture of Emacs, but then I saw multiple-cursors, which does exactly this for the secondary cursors (assuming you prevent the scrolling functions from acting on the secondary cursors). Is it maybe possible to use multiple-cursors to have the main cursor in some hidden buffer, and the effective cursor being what I actually edit with?  Or maybe some other clever trick? Or maybe my Googling has failed me and this is really already possible without any magic?
Comment: Probably not. This is the closest I can recommend: http://superuser.com/questions/184340/emacs-how-to-return-to-last-position-after-scroll-page-up-down
Comment: Note that you can always go back to **any** previous cursor position with `C-u C-space` (i.e. scroll to wherever you need to scroll, and return to wherever you were originally with this command)
Answer: There is a new package available on GNU ELPA called scroll-restore that attempts to remedy this problem.  So far, I have encountered a few bugs, but the package seems to work as-advertised for the most part.
You can test it out by installing it with
M-x package-install RET scroll-restore RET

After the package is installed, you can enable the minor mode with
M-x scroll-restore-mode

Personally, I am binding it to the Scroll Lock key because it seems so incredibly apropos! This is what I am adding to my init file:
(require 'scroll-restore)
(scroll-restore-mode 1)
;; Allow scroll-restore to modify the cursor face
(setq scroll-restore-handle-cursor t)
;; Make the cursor invisible while POINT is off-screen
(setq scroll-restore-cursor-type nil)
;; Jump back to the original cursor position after scrolling
(setq scroll-restore-jump-back t)
;; Toggle scroll-restore-mode with the Scroll Lock key
(global-set-key (kbd "<Scroll_Lock>") 'scroll-restore-mode)

This is a direct copy of an answer posted here: https://emacs.stackexchange.com/a/2273/93
Comment: Does this require 24.4? It didn't show up in the list when I was using 24.3.
Comment: I am running it on 24.3.  The package was just released for the first time on 2014-10-16, so you will have to make sure to refresh your package list.  I don't know how ELPA works, but if it uses mirrors at all, it is possible that the package has not reached all of the mirror.  You can also download [`scroll-restore.el`](http://elpa.gnu.org/packages/scroll-restore-1.0.el) from the GNU ELPA website and add it to your site-lisp.
Comment: my cursor doesn't turn back to visible. Any suggestions?
Comment: Yeah, this package is barely usable. It's WAY too buggy.
Answer: Strictly, speaking you can't move the cursor offscreen, because the underlying C code won't let you do it.
This said, I suspect that your problem can be fixed.  Basically, there are 2 aspects:

you don't like the way things look when "the cursor is pushed forward".  You could work around that by (temporarily) making the cursor invisible.
you want to "jump back" to the pre-scrolling position as soon as you issue a non-scrolling command.  There's probably some package out there that does it for you, but you can do it yourself with some pre-command-hook hacking.

BTW, I'd welcome patches in Emacs which provide some of that functionality.  I hate the "auto jump-back" behavior of other editors, but it would be good to record the "pre-scroll" position and then offer a way to jump back to it.
Comment: Yes I think a combination of those two bullet points would give me exactly what I want.
Comment: Is there any way to hook into the functions that move the cursor when scrolling?  Specifically, is there a hook that could notify me *before* the location of `point` is modified by a scrolling command?  Also, in which C files from the Emacs source can I find the code that defines this behavior?
Comment: @nispio: I don't think there's such a hook yet.  IIRC at the time when Emacs decides that point needs to be moved to stay on-screen, we can't easily run Elisp code, but we could probably stash the position of point somewhere.  Could you `M-x report-emacs-bug` requesting such a feature?
Comment: Done. Do you know approximately where I might look in the C sources to find the current implementation?
Answer: Judging by the context and description of your problem, it looks like you want to browse the buffer while preserving your place of editing. There are at least two tricks for that purpose: marks/registers and splitting in two windows.
https://stackoverflow.com/a/3777598/308668 describes the Emacs' registers that act like Vim's marks. You can check in your place in the file with keying C-x r SPC a (a being a letter of your choice) and you can always come back with C-x r j a.
Some sort of automation is achieved by an external script (goto-last-change.el), described here: https://superuser.com/a/184402/49046.
Alternatively, split the window in two with C-x 2. The newly split windows both show the same location and you can use the other to explore. C-x 0 closes a window when you're done.

Let Emacs move the cursor off-screen


Gradient of $∇x: A^2x$

Question: Let $x ∈ \mathbb R^n$ and $A ∈ \mathbb R^{n×n}$
What is the gradient $∇x:A^2x$?
I see a rules that often used when differentiating multivariate functions:
For all  $A∈\mathbb R^{m×n}$ ,  $∇x:Ax=A^⊤$,
So I process the $x: A^2x$ to $∇x: A(Ax)$ and use previous rules
It becomes  $A  A^⊤$
Is it correct?
If not, what should I do with it?
Comment: Welcome to MSE. You should use Latex to edit your question in this site. This is definitely needed for your question as there're too many ambiguities without Latex.
Comment: Do you want the gradient $\nabla x:A^2x$, or the gradient *of* $\nabla x:A^2x$? Part of me suspects you want $\nabla_xA^2x$.
Comment: @J.G. Yes, ∇xA2x .
Comment: Please use MathJax in comments too.
Comment: Sorry, it is my first time to use this site. I'm not very familiar with some specific operations
Comment: See  https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference ,
Comment: When you write "What is the gradient of $\Psi$?" then $\Psi$ should be a scalar function of an obvious vector variable, say $x$. But $\Psi:=\ \nabla x : A^2 x$ is no such function. In fact this $\Psi$ makes no sense at all.
Comment: I only suggested MathJax in comments because when I asked which of multiple possibilities is applicable, your reply left me none the wiser. Was my first idea right, the second, the third?
Comment: With $M:N$ you mean $M:N=\text{tr}(M^TN)$?
Comment: @J.G. You said, "Part of me suspects you want ∇xA2x." That is what I want.
Comment: Ah, the third. See my answer.
Answer: Since $\nabla_xAx=A^T$, $\nabla_xA^2x=(A^2)^T=(A^T)^2$.
Comment: Can you give a brief explanation about why ∇x A2x= (A2)T?
Comment: I previously thought it would be A*AT
Comment: @YahuWang I'm just replacing $A$ with $A^2$ in the identity. Maybe using different letters would help: take $B=A^2$ in $\nabla_xBx=B^T$.
Comment: Oh, that looks to make more sense, thank you!

Gradient of $∇x: A^2x$


Mostrar informações do DB através do combobox

Question: Estou uns dias procurando na internet e não sei se estou procurando de uma maneira errada só sei que não estou conseguindo achar o que preciso.
Seguinte: Eu gostaria de ao clicar em uma das opções que esta na ComboBox(ou menu/list), que me mostrasse o resultado logo abaixo.
Exemplo: tenho uma ComboBox com prioridade "Alta", "Média", "Baixa" e "Todos". Assim que eu clicar em uma dessas opções abaixo me mostra imediatamente os resultados de acordo com o que cliquei e que se encontra cadastrada no Mysql.
Alguém poderia me ajudar? Estou usando a linguagem PHP apenas, mas caso necessite de javascript se puder me explicar como aplicar vou agradecer muito.
OBS: Eu não quero pegar os dados que esta no Mysql e por no Select. Eu quero é que ao clicar em uma das opções que já esta no select eu visualize abaixo o que esta no Mysql.
Coloquei essa "OBS" porque o que eu só achei ate agora foi como preencher o combobox sendo que quero é o contrario.
Comment: Acho que [essa](http://pt.stackoverflow.com/q/32357/91) e [esta outra](http://pt.stackoverflow.com/q/23118/91) resposta podem ajudar a resolver o seu problema. Aproveite e veja  como site funciona na [tour](http://pt.stackoverflow.com/tour).
Answer: //Funções utilizadas

function conectar_banco_mysql(){
    $dsn = "mysql:host=localhost;dbname=seu_bd";
    $username = "root";
    $passwd = "";
    $pdo = new PDO($dsn, $username, $passwd);
    return $pdo;
}

function listarCategorias($tabela) {
    $pdo = conectar_banco_mysql();
    $listar = $pdo->query("select distinct categoria from $tabela ORDER BY categoria ASC ");
    $dados_encontrados = $listar->fetchALL(PDO::FETCH_OBJ);
    return $dados_encontrados;
}

<form method="post" action="">

Busca

Categorias

                <input  type="hidden" name="local" value="" />
                <select class="input1" type="text" size="7" style="width:600px; background-color: #fff; color:#000; padding-left: 15px;" name="categoria" >
                    <?php
                    $categorias_encontradas = listarCategoria("nome_sua_tabela");
                    if (!empty($categorias_encontradas)):
                        foreach ($categorias_encontradas as $local):
                            // print_r($local);
                            ?>
                            <option value="<?php echo $local->categoria ?>"><?php echo $local->categoria ?>
                                <?php
                            endforeach;
                        else:
                            ?>
                            Nenhuma entrada para processar!
                        <?php
                        endif;
                        ?>
                </select>

                <input class="btn btn-success" type="submit" value="pesquisar">

            </form>
            <?php
            @$busca = filter_var($_POST['categoria'], FILTER_SANITIZE_MAGIC_QUOTES);
// print_r($busca);
            if (!empty($_POST['categoria'])): //para obter o nome da categoria
                $tarefas_encontradas = listarBusca('sua_tabela', $busca);
                foreach ($tarefas_encontradas as $caixa):
                    //  print_r($caixa);
                    ?>

                        Tarefa n&#186  <?php echo $caixa->id_coluna_tabela; ?> |
                        Projeto n&#186 <?php echo $caixa->num_projeto_coluna_tabela; ?>

                        Data agendada: <?php echo $caixa->data_alvo_coluna_tabela; ?>

                        Última atualização:  <?php echo $caixa->data_coluna_tabela; ?>

Categoria: <?php echo $caixa->categoria_coluna_tabela; ?>

                        Resumo:

<?php echo $caixa->titulo_resumido_coluna_tabela; ?>

                        Descrição:

<?php echo $caixa->hist_coluna_tabela; ?>

                        <input class="btn btn-mini btn-info" type="button" VALUE="► Editar" onclick="location.href = '?p=actplan_alter&id=<?php echo $caixa->id; ?>';">
               <?php
                endforeach;
                ?>
                <?php
            else:
                echo '
Nenhuma categoria selecionada!

Selecione CLASSIFICAR para ver tarefas sem categoria';
            endif;
            ?>


GAE CGI: how to response http status code

Question: I am using google appening, it's CGI environment. I want block some request, I want response nothing  even no http status code. Alternative, I want just close the connection. Can I do this?
update:
I have decide to use what pyfunc said, use 204 status, but how can I do this at GAE CGI environment without any webframework.
update 2:
Thanks a lot, but... I really need a CGI way, not WSGI way. Please see the comment in my codes.
def main()
  #Block requests at once.
  if (settings.BLOCK_DOWNLOAD and os.environ.get('HTTP_RANGE')) \
        or (settings.BLOCK_EXTENSION.match(os.environ['PATH_INFO'])):
    #TODO: return 204 response in CGI way.
    #I really do not need construct a WSGIApplication and then response a status code.
    return

  application = webapp.WSGIApplication([
    (r'/', MainHandler),
    #...
    ], debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()

Answer:
The HTTP status code is important in response

You can use HTTP NO CONTENT 204 to responde with empty content.
You could use 403 Forbidden but I prefer 204 to make a silent drop of request
You could loose connection but that would be rude and can result in server being pounded with connections as user may retry.

[Edit: updated question]
You can look at many a examples on SO tagged with GAE:

https://stackoverflow.com/questions/tagged/google-app-engine

It is my understanding that you will be using webapp framework. Beef up on it's usage.

http://code.google.com/appengine/docs/python/tools/webapp/

Check how to set response object status code at

http://code.google.com/appengine/docs/python/tools/webapp/redirects.html

Here is an example of bare bone server that responds with 204 no content. I have not tested it, but it would be in similar lines.
import wsgiref.handlers
from google.appengine.ext import webapp
class MainHandler(webapp.RequestHandler):
    def get(self):
        return self.response.set_status(204)

def main():
    application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
    wsgi.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

See a complete application at :

http://code.google.com/p/pubsubhubbub/source/browse/trunk/hub/main.py?spec=svn335&r=146#1228
Comment: 403 forbidden makes a lot more sense than 204 no body.
Comment: @Nick Johnson: Yes, But we had to block certain bad clients, we have used 204 No Content
Comment: But why aren't you using 403 instead? It'll still block them, but it's more correct. Also, don't forget about the DoS API, which does this for you.


Why is Bach's Cello Suite 1 written in 16th notes

Question: I come from a blues/rock background and play some jazz too. Recently I started to learn Bach's cello suite 1 on bass guitar, and I am confused by the way I am supposed to feel the rhythm. If I were to write it down, I would do using 8th notes, because of the following reasons:

It feels much more natural for me to tap my foot to every second note
I feel every measure in the way it is normally written as two measures.

Is there a specific reason that it is written in 16ths, or am I supposed to be feeling the rhythm differently?
Comment: I'm not sure, which movement you are talking about, but the first three are typically played quite fast; if you tap your foot every second note, then (even in case you are not slowing down too much) you may atomize the intended melodical lines. The suites are to be played in the spirit of dances.
Comment: I am currently working on the prelude.
Comment: For curiosity's sake, what printed time signature does the prelude of Bach's Cello Suite 1 use?
Comment: why is Bach's Air written in 32nds? I don't know. He could have saved a lot of ink!
Comment: Classical pieces tend to have much longer melodic phrases and structures than rock/blues does.  As you study and learn (listen to!) material from 1200 CE thru the 19th or 20th century, you'll find phrases which run for many measures, even tho' there is an underlying emphasis pattern.
Answer: Music notation conventions have changed, at different times in history.
Bach did not give any tempo indication for the prelude and wrote it in common time. Therefore the written "beat" was a quarter note, i.e. every four written notes.
In Bach's time, musical tempos were defined relative to the human heart beat, not as MM values (the metronome had not yet been invented). Some contemporary books on music theory compared the pulse rate with the length of a swinging pendulum, which gives the default tempo at that time (and the average heartbeat rate of musicians!) as about 80 beats per minute. The practical range of tempi varied from two musical beats in three heartbeats (i.e. about 54 BPM) to three musical beats in two heartbeats (i.e. about 120 BPM).
Modern dance music tends to use faster tempi but with fewer subdivisions, so your instinct to count 2 notes to a beat and not 4 is probably not too far from the historically "correct" performance speed. But a classical musician would probably "feel" the rhythm of this piece with only two (slow) or one (very slow) beats in each bar - i.e. the "beats" correspond to the "chord changes" in the music, not to some faster rhythm.
In music of Bach's time, the shortest written notes in different pieces tended to be of similar duration, independent of the tempo in "beats per minute." Thus, "slow" pieces (in terms of BPM) were often written in shorter note values than "fast" pieces. In the absence of precise tempo markings (no metronomes!) this was a useful visual clue as to the character of the music - the score of a "slow" piece would typically have lots of 16th and 32nd notes, while a "fast" one would be written mostly in quarters and 8ths.
Comment: This is fascinating material!  Your answer would benefit from the addition of a few references / citations,  just to help validate this information.


How to restrict a Linux program's permissions

Question: I'm running a native linux program from PHP using shell_exec. Specifically, calling antiword to extract text from Microsoft Word files users uploaded. However, as I've got no way of assessing anbiword's code quality, and it is being fed unsanatised user input (the Word file), I would like to restrict it's permissions.
It should for example only be allowed to read files and output text on the standard output, but not to write or delete any files.
Is there any known way to "wrap" or otherwise restrict a program's such as antiword when called from PHP or on the command line?
So far I've found AppArmor which seems to be able to provide this functionality, albeit not simply, and not on the fly from the commandline.
Comment: Look into SELinux, Chroot, Systrace, and Linux Containers, lots to choose from.
Comment: To clarify, are you trying to sanitize the return values from anbiword back into your PHP script or prevent anbiword itself from running bad code?
Answer: This is what the selinux sandbox was built for. Here is the documentation for sandbox. There's also been work on accomplising the same thing with containers or virtualization in the virt-sandbox project.


Multiples meta_key and order by specific meta_value

Question: I am trying to get the posts order by a meta_value that i put in a sortable list of posts, i have an extra meta_key and meta_value to give extra info to the query, but i can't make the WP_Query return the post order, do you have any idea that whats is worng?
This is my WP_QUery code:
<code>$args = array(
    'meta_query' => array(
        array(
            'key' => 'portada',
            'value' => 'on'
        ), array(
            'key' => 'pos',
            'type' => 'numeric'
        )
    ),
'meta_key' => 'pos',
'orderby' => 'meta_value_num');
$loop = new WP_Query($args);
</code>
Answer: i use the follow code to solve my problem:
<code>$args = array(
   'meta_query' => array(
       array(
          'meta_key' =>'destacados',
          'meta_value' => 'on'
       )
    ),
    'orderby' => 'meta_value_num',
    'category__in' => $category->cat_ID,
    'meta_key' => 'pos'
);
$loop = new WP_Query($args);
</code>
Thank you all :)
Answer: Note that
<code> 'meta_query' => array(
       array(
          'key' =>'destacados',
          'value' => 'on'
       )
    )
</code>
instead of
<code>'meta_query' => array(
       array(
          'meta_key' =>'destacados',
          'meta_value' => 'on'
       )
    )
</code>


UIGestureRecognizer - Get the reference to the touched UIViewController Instead of its View?

Question: How do I get a reference to the UIViewController of a touched view?
I am using a UIPanGestureRecognizer on the view of a UIViewController. Here's how I initialize it:
    TaskUIViewController *thisTaskController = [[TaskUIViewController alloc]init];
    [[self view]addSubview:[thisTaskController view]];
    UIPanGestureRecognizer *panRec = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
    [[thisTaskController view] addGestureRecognizer:panRec];

In the tiggered action triggered using the gesture recognizer I am able to get the view from the parameter using recognizer.view
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
    UIView *touchedView = [[UIView alloc]init];
    touchedView = (UIView*)[recognizer view];
    ...
}

However what I really need is the underlying UIViewController of the view touched. How can I get a reference to the UIViewController that contains this view instead of only the UIView?
Answer: [touchedView nextResponder] will return the UIViewController object that manages touchedView (if it has one) or touchedView's superview (if it doesn't have a UIViewController object that manages it).
For more information, see the UIResponder Class Reference.  (UIViewController and UIView are subclasses of UIResponder.)
In your case, since you happen to know that touchedView is your viewController's view (and not, for instance, a subview of your viewController's view), you can just use:
TaskUIViewController *touchedController = (TaskUIViewController *)[touchedView nextResponder];

In the more general case, you could work up the responder chain until you find an object of kind UIViewController:
id aNextResponder = [touchedView nextResponder];

while (aNextResponder != nil)
{
  if ([aNextResponder isKindOfClass:[UIViewController class]])
  {
    // we have found the viewController that manages touchedView,
    // so we break out of the while loop:
    break;
  }
  else
  {
    // we have yet to find the managing viewController,
    // so we examine the next responder in the responder chain
    aNextResponder = [aNextResponder nextResponder];
  }
}

// outside the while loop.  at this point aNextResponder points to
// touchedView's managing viewController (or nil if it doesn't have one).
UIViewController *eureka = (UIViewController *)aNextResponder;

Comment: Thanks. That looks like the right direction. I tried to use it like this:
TaskUIViewController *touchedController = [[TaskUIViewController alloc]init];
    touchedController = (TaskUIViewController*)[touchedView nextResponder];
    NSLog(@"Recognizer: %@",touchedController);
I still get a pointer to a UIView back not a UIViewController. Did I address it correctly?
Comment: @BerndPlontsch  You don't need to alloc/init a new `TaskUIViewController`.  Just use `TaskUIViewController *touchedController = (TaskUIViewController *)[touchedView nextResponder];`  (See the sample code that I have added in my expanded answer above.)
Answer: I would say that it is more a design issue than just getting a reference. So I would follow several simple advises:

Owner should catch events from its view. I.e. TaskUIViewController sould be a target to UIPanGestureRecognizer which you added to its view.
If a controller has a sub-controller and waits from its sub-controller some responses - implement this as delegate.
You have memory leak in your "handlePan:" method.

Here is a skeleton to solve your issue:
@protocol CallbackFromMySubcontroller <NSObject>
- (void)calbackFromTaskUIViewControllerOnPanGesture:(UIViewController*)fromController;
@end

@interface OwnerController : UIViewController <CallbackFromMySubcontroller>
@end

@implementation OwnerController

- (id)init
{
    ...
    TaskUIViewController *thisTaskController = [[TaskUIViewController alloc] init];
    ...
}

- (void)viewDidLoad
{
    ...
   [self.view addSubview:thisTaskController.view];
    ...
}

- (void)calbackFromTaskUIViewControllerOnPanGesture:(UIViewController*)fromController
{
    NSLog(@"Yahoo. I got an event from my subController's view");
}

@end

@interface TaskUIViewController : UIViewController {
    id <CallbackFromMySubcontroller> delegate;
}
@end

@implementation TaskUIViewController

- (id)initWithOwner:(id<CallbackFromMySubcontroller>)owner
{
    ...
    delegate = owner;
    ...
}

- (void)viewDidLoad
{
    UIPanGestureRecognizer *panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.view addGestureRecognizer:panRec];
    [panRec release];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    ...
    [delegate calbackFromTaskUIViewControllerOnPanGesture:self];
    ...
}

@end

Comment: Thanks a lot. What you write makes much sense to me. However with the GesturerRecognizer inside the UIViewController, the program now crashes as soon as I trigger the pan event with a "EXC_BAD_ACCESS..." error. Unfortunately not more hints on the cause are provided. Any idea on this?
Comment: Just check if you set correct target inside gesture as well as correct handler. There is no magic, just a code :)
Comment: I did it as you proposed "UIPanGestureRecognizer *panRec = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];" all within the UIViewController's viewDidLoad method. The "handlePan" method exists as well... puzzling
Comment: Try to replace IBAction with void inside handlePan: method name. I fixed the code. Check also if you have no links from some XIB to this handlePan:. I corrected the code example.
Comment: Sorry, still getting the "EXC_BAD_ACCESS..." error. I am trying to ask another question giving more details on my implementation. But I think your approach shows the right way. So again, thanks for that.
Comment: @VyachaslavGerchicov: I think you have to submit another question, man. I answered to exact question with my suggestion.
Comment: @VyachaslavGerchicov: So you down-voting the answer because in new circumstances you just brought up it looks incomplete?
Comment: @SVGreg you haven't simply answered the question. You add gesture recognizer inside view controller you need and this controller contains a gesture handler method. So you just write `self` which is a pointer to your controller and so you can call any method inside it. Other code you wrote is extra. And of course the question doesn't say that this code is inside another view controller. So your case occurs frequently but it is particular
Comment: @VyachaslavGerchicov: I'm not sure you've got a point. My code is not exact implementation but rather a sketch which describes the idea. If you have better one - just submit it. I do not see any answer from you.
Comment: @SVGreg Ok. You store a link to view a link to its owner controller - property, "associated object" and etc. It is normal because the owner controller's lifetime is longer than its view


Is there any way to mapping a AllowHtml attribute with fluent API? (ASP.NET MVC)

Question: <code>public class Body
{
    [AllowHtml]
    public string HtmlContent { get; set; }
}
</code>
Is there any way to mapping with fluent API?
Answer: It is actually a good question. I have similar problem too. I have a library with POCO classes for my Data Layer. [AllowHtml] attribute requires referencing System.Web.MVC which is supposed to be used in Presentation (UI) Layer. Is there some way how to decorate some property with [AllowHtml] attribute outside a Data Layer Class? I would like to avoid using [ValidateInput(false)] in my controller's Actions.
(I know, that Data Layer classes should not be used in UI Layer, but some of them are useable.)
Answer: You can add the [AllowHtml] attribute to a view model and use that view model in the controller and view as described in this answer


UISearchBar's Cancel button issue in iOS 6

Question: I am using UISearchBar, but i am getting problem in cancel Button in iOS 6, which works fine in iOS 7
 For iOS 6
For iOS 7
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:whiteColor];

In iOS 7, Button's border doesn't shows up. Only "Cancel" is written with white color.
In iOS 6, Button with its border appears with whole background also white. Please help.
Answer:
If I understand you correctly, you want to make the button's background transparent and have no border. If so, I think I found a solution:
For iOS6:
You have to set the backgroundImage property to image with a transparent background.
For example you can do it with an UIImage object made with [UIColor clearColor].

For iOS7:
Just change nothing, but tintColor :)

How to do it?
Firstly, I used a method from here: LINK, but changed it a little bit to:
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

Then in viewDidLoad I wrote:
if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 7.0) {
        [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundImage:[self imageWithColor:[UIColor clearColor] andSize:CGSizeMake(30.f, 40.f)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    } else {
        [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTintColor:[UIColor whiteColor]];
    }

I hope it will solve your problem :)


Hiding Eggs Combinatorics

Question: How can I figure out if I have 6 red eggs, 3 blue eggs, 1 green egg, and 2 yellow eggs. Aside from their color, they are identical. I have 12 different hiding spots, each big enough for 1 egg. How many ways are there to hide the eggs?
Answer: HINT: How many ways are there to choose $6$ of the $12$ hiding places for the red eggs? Once you've done that, how many ways are there to choose $3$ of the remaining hiding places for the blue eggs? Keep going in this fashion and combine the answers correctly, and you'll have your answer.
Comment: So this leads me to think I want to do 12C6 * 6C3 * 3C1 * 2C2. Is this how I would combine them correctly?
Comment: @Nate: Yes, that's exactly right.
Answer: Hint(In terms of Combinatorics): How many ways can you partition 12 items in groups of 6, 3, 2 and 1?

Hiding Eggs Combinatorics


Make variables outside of node available to pathauto

Question: I'm trying to port a website over to Drupal 7. The structure consists of locations which have an entity reference to a region which has an entity reference to a country:

location<-region<-country<-continent

This all seems to work OK. A location node doesn't directly know what country it is in, but it does know what region it's in.
The problem is I want to use the old URL structure:

/continent/country/region/location

So far I can get it to work for /region/location (as region is referenced from location) but then I get stuck.
What I'm wondering is there any way to pull these other fields (country / continent) into the node and make them available to pathauto?
If it helps it doesn't really matter what the continent and country are as region & location provide enough info. So a wildcard would be fine.
So, firstly, is this possible with this structure. And if so, how?
Any help greatly appreciated.
Answer: I was in a similar boat with a site I was working on recently.  Unfortunately, Drupal 7 does not fully support tokens on field entities; see http://drupal.org/node/691078.  This is why the "location node" type exists in the location module -- it is easier to define tokens for your locations.  However, I did not like the UX for location nodes; I greatly preferred the result that can easily be obtained with cck locations.
Since it was not possible to easily support tokens on cck locations, I instead wrote my own custom token code in my custom module for my site. I did spend quite a few hours trying to do the former first, before giving it up as much too large of an effort.
I'm not sure if you are using the location module, or if you are just defining your own entities that happen to contain locations.  The fact that you have your location entities chained together implies that you're using your own entity types.  Here's the result I came up with for the location module; you should be able to adapt it for standard entities without much trouble.  The code below could probably use some minor improvements; 'und' should be LANGUAGE_NONE, the special-checking for a specific content type is probably unnecessary, etc.; it shouldn't be too hard for you to adapt in some code that resolves your chained entity references to build the tokens you need.
Once you've written your code, it's easy to select your new tokens in pathauto to define your URL structure.
function MYMODULE_token_info() {
  // Because of http://drupal.org/node/691078, we just hack in our own
  // field-based tokens here for now (cough).
  // These tokens are only available for nodes of type MY_CONTENT_TYPE_WITH_LOCATION_FIELD
  $node['field_location_street'] = array(
    'name' => t("Location Street"),
    'description' => t('The street address that a location is located at.'),
  );
  $node['field_location_city'] = array(
    'name' => t("Location City"),
    'description' => t('The city that a location is in.'),
  );
  $node['field_location_province'] = array(
    'name' => t("Location Province"),
    'description' => t('The abbreviation for the province (State) that a location is in.'),
  );
  $node['field_location_province_name'] = array(
    'name' => t("Location Province Name"),
    'description' => t('The full name of the province (State) that a location is in.'),
  );
  $node['field_location_country'] = array(
    'name' => t("Location Country"),
    'description' => t('The country that a location is in.'),
  );
  $node['field_location_country_name'] = array(
    'name' => t("Location Country Name"),
    'description' => t('The full name of the country that a location is in.'),
  );
  $node['field_location_summary'] = array(
    'name' => t("Location Summary"),
    'description' => t('A parenthesized summary of the location (City, State).'),
  );
  return array(
    'tokens' => array('node' => $node),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $location_field = array();
    if (($node->type == 'MY_CONTENT_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_location['und'][0]))) {
      $location_field = $node->field_location['und'][0];
    }
    if (($node->type == 'MY_CONTENT_TYPE_WITH_NODE_REF_TO_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_event_site['und'][0]))) {
      $location_nid = $node->field_event_site['und'][0]['nid'];
      $location_node = node_load($location_nid);
      if (isset($location_node->field_location['und'][0])) {
        $location_field = $location_node->field_location['und'][0];
      }
    }
    if (!empty($location_field)) {
      $location_field['summary'] = "(" . $location_field['city'] . ", " . $location_field['province'] . ")";
      foreach ($tokens as $name => $original) {
        if (substr($name,0,15) == 'field_location_') {
          // $name is always 'field_location_xxx', so key is 'xxx'.
          $key = substr($name, 15);
          if (isset($location_field[$key])) {
            $replacements[$original] = $location_field[$key];
          }
          else {
            $replacements[$original] = '';
          }
        }
      }
    }
  }
  return $replacements;
}

Comment: Hi Greg. Thanks for the reply. I was hoping there was a nice easy solution without having to get under the hood as this is my first Drupal project.
I'll probably accept the answer once I've digested what it entails and get my head around that. But it looks like the kind of thing I was imagining.

I do use the location module but I don't want to have to put in region / country data here as it would be duplicated .

Still, once I get the URLs cracked it's pretty much just theming it up...

Thanks
Comment: I tweeted about this question. We'll see if anyone comes by with a better answer.


Proving convergence by the comparison test

Question: I need to prove the convergence of the following series :
$$\sum_{n=1}^{\infty} \frac{1}{(3n-2)(3n+1)}$$
I suppose I need to find two series like
$$\sum_{n=1}^{\infty}(k_1a_n + k_2b_n) = \sum_{n=1}^{\infty} = k_1\sum_{n=1}^{\infty}a_n  + k_2\sum_{n=1}^{\infty}b_n$$
I thought that the series $a_n$ and $b_n$ can be the partial sums, so
$$\sum_{n=1}^{\infty} \frac{1}{(3n-2)(3n+1)} =  \frac{1}{3}\sum_{n=1}^{\infty} \frac{1}{(3n+1)} - \frac{1}{3}\sum_{n=1}^{\infty} \frac{1}{(3n-2)}$$
I know, by the comparison test, that if $a_n$ and $b_n$ converge, the main series will it too. But, how can I demonstrate that the series $a_n$ and $b_n$ converge?
Comment: Your partial fraction step is wrong. It should be a minus instead of a plus and neither $a_n$ nor $b_n$ converges.
Comment: telescopi rule$$\sum_{n=1}^{\infty} \frac{1}{(3n-2)(3n+1)} = \frac{1}{3}\sum_{n=1}^{\infty} \frac{-1}{(3n-2)} + \frac{1}{3}\sum_{n=1}^{\infty} \frac{1}{(3n+1)}$$
Comment: For completeness on this question, we should note that the two sums $a_n$ and $b_n$ do _not_ converge.
Answer: One may just observe a telescoping sum here

$$
\sum_{n=1}^N \frac{1}{(3n-2)(3n+1)}=\frac13\sum_{n=1}^N \left(\frac{1}{3(n-1)+1}-\frac{1}{3n+1}\right)=\frac13-\frac{1}{3(3N+1)}
$$

giving the convergence and the sum of your initial series.
Comment: This is of course a nice answer.  Probably one should include the comments that (i) it does not use the comparison test and (ii) it is somewhat "lucky" that it turns out to be a telescoping su can be mevaluated exactly.  The larger class of series of the form $\sum_n \frac{ f(n)}{g(n)}$ for polynomials $f$ and $g$ which can be evaluated using the comparison test and the "$p$-series test", and very rarely by a telescoping sum.
Answer: For $n\ge 1$, $3n+1>n$ and for $n\ge 2$, we have $3n-2>n$.  Hence,
$$\frac1{(3n-2)(3n+1)}<\frac1{n^2},\quad \text{for }n\ge 2.$$
Comment: good ol' $\dfrac{\pi^2}{6}$