Como eu descrevo uma equação da reta de um glmm em um gráfico xy no R?

Question: Olá,
tenho dados de idade (X) e riqueza de espécies por amostra (y). Fiz um glmm e gostaria de saber como escrever a equação de forma correta na figura no R. Alguém tem algum site/paper para indicar?
Obg,
Answer: Existem várias formas de incluir a equação na figura, a depender de como você está plotando o gráfico. Aqui seguem alguns exemplos, caso queira uma resposta mais específica para o seu problema, favor inserir o código que você criou.
Usando plot:
x<- runif(1000, min = 0, max=5)
y<- pi + x^2
plot(x, y, main= expression(Gráfico ~ da ~ Equação ~ pi + x^2))

Gera a figura:
Usando ggplot:
library(ggplot2)
library(ggpmisc)
dados <- data.frame(x = c(1:100))
dados$y <- pi + dados$x^2 + rnorm(100, sd = 500)
minha.formula <- y ~ x
ggplot(data = dados, aes(x = x, y = y)) +
  geom_point()+
  geom_smooth(method = "glm", se=FALSE, color="blue", formula = minha.formula) +
  stat_poly_eq(formula = minha.formula,
               eq.with.lhs = "italic(hat(y))~`=`~",
               aes(label = paste(..eq.label.., ..rr.label.., ..AIC.label.., sep =  "*plain(\",\")~")),
               parse = TRUE) +
  labs(title= expression(Gráfico ~ da ~ Equação: ~ pi +x^2))

Gera a figura:

Espero ter ajudado :)
Comment: Oi Marina. Muito boa a sua dica.
Comment: olá, gostei muito dessa solução, porém gostaria de saber se tem como colocar as significâncias dos coeficientes, tentei localizar de onde a função `stat_poly_eq`, retira `..eq.label..` porém não tive êxito, você saberia se tem como colocar?
Comment: Olá @JeanKarlos, `stat_poly_eq` computa `x`, `y`, `eq.label`, `rr.label`, `adj.rr.label`, `AIC.label` e `BIC.label` (veja a [documentação](https://cran.r-project.org/web/packages/ggpmisc/ggpmisc.pdf)). Existem outras formas de colocar fórmula e outras informações no gráfico. [Esse post](https://stackoverflow.com/questions/7549694/adding-regression-line-equation-and-r2-on-graph) no SO em inglês tem um exemplo com a inclusão do p-valor.


Java app & C++ app integration / communication

Question: We have two code bases, one written in C++ (MS VS 6) and another in Java (JDK 6).
Looking for creative ways to make the two talk to each other.

More Details:
Both applications are GUI applications.
Major rewrites or translations are not an option.
Communications needs to be two-way.
Try to avoid anything involving writing files to disk.
So far the options considered are:

zero MG
RPC
CORBA
JNI
Compiling Java to native code, and then linking

Essentially, apart from the last item, this boils down to a choice between various ways to achieve interprocess communication between a Java application and a C++ application. Still open to other creative suggestions!
If you have attempted this, or something similar before please chime in with your suggestions, lessons learnt, pitfalls to avoid, etc.

Someone will no doubt point out shortly, that there is no one correct answer to this question. I thought I would tap on the collective expertise of the SO community anyway, and hope to get many excellent answers.
Comment: In situations like these, where rewrites are undesirable and you would have to write the JNI glue-code, I'd highly recommend [considering JNA, and writing the JNA glue-code](http://stackoverflow.com/questions/2241685/java-native-access-doesnt-do-c-right/2242341#2242341), it's simpler, IMO.
Comment: @bguiz: How have you been going with this? Any of the suggestions been of assistance?
Answer: Well, it depends on how tightly integrated you want these applications to be and how you see them evolving in the future. If you just want to communicate data between the two of them (e.g. you want one to be able to open a file written by the other, or read a stream directly from the other), then I would say that protocol buffers are your best bet. If you want the window rendered by one of these  GUI apps to actually be embedded in a panel of the other GUI app, then you probably want to use the JNI approach. With the JNI approach, you can use SWIG to automate a great deal of it, though it is dangerously magical and comes with a number of caveats (e.g. it doesn't do so well with function overloading).
I strongly recommend against CORBA, RMI, and similarly remote-procedure-call implementations, mostly because, in my experience, they tend to be very heavy-weight and consume a lot of resources. If you do want something similar to RMI, I would recommend something lighter weight where you pass messages, but not actual objects (as is the case with RMI). For example, you could use protocol buffers as your message format, and then simply serialize these back and forth across normal sockets.
Kit Ho mentioned XML or JSON, but protocol buffers are significantly more efficient than either of those formats and also have notions of backwards-compatibility built directly into the definition language.
Comment: that's what DDS is for (pub/sub)
Answer: Use Jacob ( http://sourceforge.net/projects/jacob-project ), JCom ( http://sourceforge.net/projects/jcom ), or j-Interop ( http://j-interop.org ) and use COM for communication.
Comment: +1 @g051051 : Thanks for the suggestions, will look into them
Answer: Since you're using Windows, I'd suggest using DDE (Dynamic Data Exchange). There's a Java library available from Java Parts.
Comment: +1 @Ben Jaguar Marshall : Thanks for the suggestion, I'll look into it
Answer: Dont' know how much data and what type of data you wanna transfer and communicate.
But to simplify the way, I suggest using XML or Json based on HTTP protocol.
Since there are lots of library for both applications and you won't spend too much effort to implement and understand.
More, if you have additional applications to talk with, it is not hard since both tech. are cross-languages.
correct me if i am wrong


Overriding the default session manager with embedded tomcat 7 java

Question: I am trying to override the tomcat session manager with an embedded tomcat.
These are the steps preformed in-order to load the context.xml that defines the manager entity.
<code>..
Context context = tomcat.addWebapp(contextPath, appBase);
File configFile = new File ("D:\\context.xml");
context.setConfigFile(configFile.toURI().toURL());
tomcat.start();
..
</code>
The session manager seems to be recognized as it's constructor is being invoked but the startInternal() method is never invoked and the session manager being used is the old tomcat session manager.
The weird thing is that when defining the same configuration in a non embedded tomcat, the session manager is being overridden without problems.
Would appriciate any help on the subject.
Answer: Non embedded tomcat uses server.xml and embedded tomcat does not uses server.xml file rather we need to pass the arguments in the method.
Comment: First of all thanks for your quick answer. Sadly I don't have a clue as to why the log files aren't being generated. Ill try looking into it when I get to that point. can you please be more specific about what arguments I need to pass using what method? Thanks again..
Comment: @user840184 - I removed the follow-on question from your answer, because it doesn't really belong there.  Feel free to ask a new question on the topic, so that others can help you out.


Is it possible to scale (increase Cores) a running GCP CloudSQL in HA configuration with zero-downtime?

Question: Is it possible to increase Cores of a running GCP CloudSQL in HA configuration with zero-downtime?
Answer: I created a new Cloud SQL PostgreSQL instance. I enabled the HA at the creation time. Latter, I modified it increasing the number of cores and I got the following message
So I really think that you will have a downtime even with HA since this one is triggered when the instance become unhealthy as is mentioned here


Bind9 forward top level domain

Question: Hi all just starting working professionally with bind9 and dns, say I have an AD/DC server (with dns) running on internal.com but my bind9 is authoritative for sub.internal.com can I do a forward zone to domain.com from my bind9 server as follows?
<code>zone "internal.com" {
    type forward;
    forward only;
    forwarders { 10.15.1.1; };
};
</code>
Answer: You can certainly do that, and it will allow your DNS to perform name resolution in the parent domain.
But you will also need a delegation in the parent zone to tell its name servers that your subdomain is managed by your name servers.

Bind9 forward top level domain


The following 3x3 matrix has three real unique eigenvalues if and only if k is between what range?

Question: I need to find a range for possible values of k in matrix A so that it has three REAL and UNIQUE eigenvalues
\begin{equation*}
A =
\begin{pmatrix}
    -1 & 1 & 0 \\
    -9 & 5 & 1 \\
    k & 0 & 0
\end{pmatrix}
\end{equation*}
I know that the characteristic equation of this matrix is:
\begin{equation*}
-\lambda^3+4\lambda^2-4\lambda+k=0
\end{equation*}
Where lambda represents the eigenvalues
I then used the following equation:
\begin{equation*}
-(\lambda-a)(\lambda-b)(\lambda-c)=0
\end{equation*}
Where a, b, and c are the three unique eigenvalues
To get that:
\begin{equation*}
a+b+c=4
\end{equation*}
\begin{equation*}
abc=k
\end{equation*}
\begin{equation*}
-ab-ac-bc=-4
\end{equation*}
I have no idea what to do now.
Answer: Given a cubic in the form
$$f(x) = A x^3 + B x^2 + C x + D$$
the discriminant is defined as
$$D(f) = -27 A^2 D^2 + 18 ABCD - 4 A C^3 - 4 B^3 D + B^2 C^2.$$
$D(f)>0\iff \text{f has 3 distinct real roots}.$
We compute $D(f)$ for your cubic, with $A= -1, B= 4, C= -4, D =k$. This gives us
$$D(f) = -27k^2+32k >0\iff 0<k<32/27.$$
Answer: The discriminant of that polynomial is $32k-27k^2$. So, your matrix will have three real distinct roots if and only if $32k-27k^2>0$, wich means that $k\in\left(0,\frac{32}{27}\right)$.
Answer: Consider the function $f(x)=x^3-4x^2+4x$. Then
$$
f'(x)=3x^2-8x+4
$$
that vanishes at $2/3$ and $2$. Since
$$
f(2/3)=\frac{8}{27}-\frac{16}{9}+\frac{8}{3}=\frac{32}{27}
$$
and
$$
f(2)=0
$$
the equation $f(x)=k$ has three distinct solution if and only if
$$
0<k<\frac{32}{27}
$$


Finding outliers on simple dataset?

Question: I'm pretty inexperienced in statistics and am wondering the best way to tackle a couple of simple questions.
I am given the following data on 1,000 hypothetical slot machines:
Attempts made, wins, payout, payout per attempt (win rate * payout)
Some slot machines have over 15,000 attempts, while others have as few as 50. Here is what I'm wondering:

What is the best way assess which machines have payout per attempt values that can be classified as outliers? Seeing as some machines have so few attempts.
How can I determine the statistical significance of a given payout per attempt value when comparing it to a specific number? For example if as a gambler I want to target machines with higher than X payout per attempts?

I am working with these values in Excel also. Thank you very much!
Comment: Is this a homework problem? If so, it should have the "self-study" tag.
Answer: Assuming roughly identical payouts, about half of the machines will provide "above average" paybacks.  If you increase your criteria from "above average" to "top 5%," then 5% or 50 will be in the top 5%; 10 will be the top 1% of paybacks.  This isn't particularly insightful for the would-be gambler.  Note that even if all the machines are genuinely identical, some will have to perform better than others, but those won't necessarily provide better results for a future game.
Another way to consider this problem is to calculate a mean payout for all 1000 machines over all tens, hundreds, thousands, etc of trials.  The overall average based on this very large amount of data is probably pretty reliable.  Then you can use a statistical test on each machine's payout and test for a mean response better than the overall mean.
Suppose that there are only two outcomes – you get all your money back plus 0.8 times your money half the time, and nothing the other half.  The average payout is 0.5 x 1.8 + 0.5 x 0 = 0.9.  Further, suppose that you observed a payout of ratio of 1.26 for a machine with 10 trials (i.e. 7 wins).  What is the probability that the machine's win ratio is really only 0.5 and that this level of winning was mere luck?  The probability of winning at least 7 times with a 0.5 win rate is 17% sum(10 choose k, k = 7..10)/2^10, interesting, but hardly statistical proof.  A payout ratio of 1.26 over 50 trials (i.e. 35 wins) is only about 0.3% likely, but this is still likely to happen in about 3 of the 1000 different machines.  Moving the payout up to 1.44 (80% sample win rate), the odds start to drop off faster.  80% on 50 trials with a machine would only happen with probability 1.2x10^(-5) or 0.0012%, probably indicating a good one to hit.  As you can see it takes a good bit of suspect data to be confident in this kind of outlier.
Or you could give up the slots and lose your money in the stock market like a "responsible" adult :)
Answer: You might try to detect the outliers using a robust method. If you are willing to assume that a majority (at least 50+$\epsilon$% of your data) is from the same distribution, then you can use this approach. In doing so, you will have to assume that there is no non-random difference between the behavior of the slot machines in the majority group: the outlier machines can behave in any strange way you like.
Many robust techniques exist, but multivariate ones tend to be computationally intensive, and even univariate ones can be complicated. Since you are restricted to Excel I propose the following.
If you want to find outliers for winrate*payout (denote this $\mathbf{X}$), and your majority is symmetrically distributed, you can use the univariate version of the Minimum Covariance Determinant (MCD). The multivariate version is more complicated, but the univariate can be obtained as follows.
The goal will be to find a subset of $n/2 < h<n$ observations that are "clean" that has the smallest variance (so it is the tightest). Since the outliers are a minority, any set of $h$ points must have at least some good observations. Therefore, if the outliers are far enough from the good data, the variance of a set of outliers plus some good values totally $h$ observations should tend to have a higher variance than an $h$-subset from the good data.

Decide on a value of $h$ that seems reasonable to you, or perform this analysis with a range of $h$ values and see what looks reasonable.
Sort your values of $\mathbf{X}$ from smallest to largest. The reason you can do this instead of trying all combinations of your observations is that the $h$-subset with the smallest variance must be a contiguous set of the sorted observations.  This simplification is why you can do it in Excel.
Compute a rolling variance of sets of $h$ observations.
Select the $h$-subset with the smallest covariance. This should have no outliers.
After you have an $h$ subset, you can define the 97.5% confidence interval around the mean of the observations in your $h$-subset and include other observations in this interval as good data. This is called reweighting.

Finding outliers on simple dataset?


How to distribute 15 distinct objects into 5 distinct boxes with at least 3 boxes empty?

Question: How to distribute 15 distinct objects into 5 distinct boxes with at least 3 boxes empty
Can someone help solve this? Is there a common formula I can use to find ways to distribute n distinct objects into K distinct boxes with at least x boxes empty
Comment: For small numbers like these, casework is fine.  You either have exactly $3$ or exactly $4$ empty boxes.  Just do each case.
Comment: *Hint:* Exactly $3$ empty= exactly $2$ having some objects, exactly $4$ empty = exactly $1$ having objects
Comment: Can you please help me illustrate a case?
Comment: Have you made progress on the problem since lulu and true blue anil gave you those hints?  If so, please update your question to show your work.
Answer: The main tool is:

$n$ distinct objects can be placed in $k$ distinct boxes in $k^n$ ways: for each of the $n$ objects, we can add it to one of the $k$ boxes.

Let's label the boxes $1,2,3,4,5$.  If you're able to answer these questions, then the rest is arithmetic:

How many subsets of size $4$ are there in $\{1,2,3,4,5\}$?
Given any subset $S \subseteq \{1,2,3,4,5\}$ of size $4$, how many arrangements are there in which the boxes in $S$ are empty, and the boxes outside of $S$ are not empty?
How many subsets of size $3$ are there in $\{1,2,3,4,5\}$?
Given any subset $S \subseteq \{1,2,3,4,5\}$ of size $3$, how many arrangements are there in which the boxes in $S$ are empty, and the boxes outside of $S$ are not empty?

The last question above is the tricky part.  For example, if the boxes are labelled $\{1,2,3,4,5\}$, and we insist on the boxes $\{3,4,5\}$ being empty, then there are $2^{15}$ arrangements (using the "main tool" above), but we also need to exclude the cases that box $1$ or box $2$ is also empty (but not both---we can't have all 5 boxes empty).


Error when trying to get information SOAP from Node.js

Question: This is working fine on php but it's not on node.js
I'm getting the following error (I replaced the actual service for clientlink
I'm not a node expert so I don't have any clue where to start on here,
Thanks for everything!!!

body: '\r\n\t\r\n\t\t\r\n\t\t\tsoap:Server\r\n\t\t\tError response (code 500 from
  clientlink/soap: <soap:Enve lope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soa
  p:Body><soap:Fault><faultcode>soap:Client</faultcode><fa
  ultstring>Unmarshalling Error: unexpected element
  (uri:"clientlink", local:"callerIp").
  Expec ted elements are
  <{}enterpriseActorId>,<{}onBelhalfOfId>,&am
  p;lt;{}externalClientId>,<{}callerIp>,<{}actorId>,&lt
  ;{}agencyIdLong>,<{}onBehalfOfId>,<{}applicationId>,&
  lt;{}actionId>,<{}agencyId>
  </faultstring></soap:Fault>
  </soap:Body></soap:Envelope>\n\r\n\t\t\r\
  n\t\r\n' },

The code on node is:
var url = 'clientlink';
  var args = {
    "context": {
      "appToken": 'MEGATOKEN'
    },
    "version": 1.0
  };

soap.createClient(url, function(err, client) {
      if (err) {
        console.log(err);
        callback(err);
        return
      }
      client.getEvents(args, function(err, result) {
          if (err) {
            console.log(err);
            callback(err);
            return;
          }
          console.log(result);
      });
    });

The code on php that is working fine!
$soapClient = new SoapClient('clientlink');
$params['context']['appToken'] = 'MEGATOKEN';
$params['version'] =1.0;
$info = $soapClient->__call('getEvents', array($params));

Thanks for reading the second thanks!! :)
Comment: Have to put that in: http://nodejsreactions.tumblr.com/post/54266850885/being-told-our-new-node-system-will-need-to-talk-with-a : D
Comment: @dollarVar that gif correlates more to the fact that we had to use mysql instead of mongo ;)
Comment: Yeah, still do not know if *not* having prepared statements is a good thing ;)
Answer: First use describe() to see what methods of the remote service are available.
//...
soap.createClient(url, function(err, client) {
  if (err) {
    // ...
  } else {
    client.describe();
  }
});

Here is an example of the output from client.describe():
{
  MyService: {
    MyPort: {
      getEvents: {
        input: {
          name: 'string'
        }
      }
    }
  }
}

Then you can call getEvents() like this:
//...
soap.createClient(url, function(err, client) {
  if (err) {
    // ...
  } else {
    client.MyService.MyPort.getEvents({name: 'value'}, function(err, result) {
      // ...
    });
  }
});

Comment: Huge thanks. Never done soap and this saved my life!


Calculate $f^{(25)}(0)$ for $f(x)=x^2 \sin(x)$

Question: Calculate $f^{(25)}(0)$ for $f(x)=x^2 \sin(x)$.
The answer is too short for me to understand, and the answer is
$- 25 \cdot 24 \cdot 8^{23}$
Comment: @DonLarynx : That would not be a better idea and i believe OP knows the definition of what it is written and what you have said is nothing more than a definition
Comment: What's the Maclaurin series for your function?
Comment: @PraphullaKoushik You can find the Maclauren series of $f(x)=x^2\sin x$ by multiplying the Maclauren series for $\sin$ by $x^2$.
Comment: **HINT** Take the derivative 25 times, then plug in "0"
Comment: @DavidMitra : I do not quite understand your idea... you need that derivative to write maclaurian series right? I am missing something I guess...
Comment: @DavidMitra : That would be very good if that is true (I do not know if you can get like that)... This is very nice thing to know... I would look into that in more detail... Thank you :)
Comment: Try using [General Leibniz rule](http://en.wikipedia.org/wiki/Leibniz_rule_(generalized_product_rule))
Comment: MacLaurin series as David Mitra said, or [Leibniz rule](https://en.wikipedia.org/wiki/General_Leibniz_rule) will also do.
Answer: $$f(x) = x^2\sin x$$
$$ = x^2 \left(x - \frac{x^3}{3!} +...- \frac{x^{23}}{23!} +...\right)$$
$$ = -\frac{x^{25}}{23!} +...$$
$$f^{(25)}(x) = -\frac{25!}{23!} + ...$$
$$f^{(25)}(0) = -600$$
WolframAlpha verifies that the $8^{23}$ should not be there.
Answer: use the leibnitz rule to find the  nth derivative of the function.
$$\frac{d^n}{dx^n}(uv) = ^nC_0u \frac{d^n}{dx^n} (v)+^nC_1 \frac{d}{dx} (u) \frac{d^{n-1}}{dx^{n-1}} v+...... ^nC_n \frac{d^n}{dx^n} (u)v$$
here $  u=x^2$ and $v=\sin x$
also note
$$ \frac{d^n}{dx^n} (\sin x)=sin(x+n\frac{\pi}{2})$$
on solving you get
$$f^{n}(x)=x^2\sin(x+n\frac{\pi}{2})+2nx\sin(x+(n-1)\frac{\pi}{2})+n(n-1)\sin (x+(n-2)\frac{\pi}{2})$$
Comment: This seems to be a very good answer as it does not use the Taylor's theorem which is probably at a higher level than Leibniz rule for differentiation. I wonder why it is becoming common to down-vote without giving even a few words of comment.
Comment: wow, very fast downvote (not mine!)
Comment: i dont know why some are interested in downvoting without even noticing the idea behind the answer.
Comment: I upvote, and I really don't understand the downvote.
Answer: The answer you have stated is wrong. It should be $-25*24$. Note that in the Taylor expansion for $f(x)$ the only non-zero term that matters is $-x^{25}/23!$.  Differentiate this last expression $25$ terms and plug in zero, you will get
$$f^{(25)}(0) = -25!/23! = -600.$$
Comment: I think it is $\frac{-x^{25}}{25!}$.
Comment: Ok get it ! There's another $x^2$ to be multiplied with !
Answer: Here is an approach. Follow the steps
i) use the identity $\sin x = \frac{e^{ix}-e^{-ix} }{2i} $
ii) use the product rule for differentition.
Note that the function $(x^2)^{(m) }$ vanishes for $m=3$.  Chech this related problem.


Any ideas how I can rewire my brain such that $\varphi \leq \psi$ "obviously" means that $\varphi$ implies $\psi$?

Question: The Boolean domain $B=\{\mathrm{False},\mathrm{True}\},$ can be viewed as a partially ordered set in two different ways. In the best approach, $\mathrm{False}$ is the least element and $\mathrm{True}$ is the greatest element. This has the effect that the lattice operations $\wedge$ and $\vee$ agree with their usual (logical) definitions; furthermore, we deduce (under this convention) that $\varphi \leq \psi$ iff $\varphi \rightarrow \psi = \mathrm{True},$ as desired. Thus, let us hereafter agree to order the Boolean domain in this way.
The problem is this. Whenever I'm thinking about the Boolean domain, I tend to think of its elements as conditions. So for example, since $\mathrm{True}$ is the weakest condition, I tend to think of $\mathrm{True}$ as the least element. But this contradicts the aforementioned ordering; we agreed that $\mathrm{True}$ should be the greatest element!
The same issue occurs when $B$ is replaced by any other poset of sentences, such as the sentences of the first-order language of arithmetic. I always get confused, because I tend to think of those sentences as conditions, and therefore I read $\varphi \leq \psi$ to mean "$\varphi$ is a weaker condition than $\psi$." (Bad!)
So, I'd like to rewire my brain so that "$\varphi$ is less than $\psi$" intuitively means "$\varphi$ implies $\psi$."
Any ideas how to do this?
Comment: Thirty years of computer programming did it for me. FALSE is 0 and TRUE is 1.
Comment: The best approach of course is to make $\bot$ the top element, not the bottom. Then stronger statements are higher in the lattice.
Comment: Maybe think of $\leq$ similarily as $\subseteq$ ? I think the analogy between the logic $\leq$ and set theory $\subseteq$ is more consistent than the analogy between numeric $\leq$ and logic $\leq$...
Comment: @Olivier, its a good suggestion, but hasn't worked for me so far. The problem is that when I read a mathematical formula, I parse it as as *formula*, not as the set of all its instances in some particular universe.
Comment: You could try reading $A \le B$ as "$A$ is no more true than $B$".
Comment: @CarlMummert, I strongly considered doing just that, but my concern is that it may create as many problems as it solves. Sure, its more intuitive; *but* for example it means that (1) $\wedge$ means "or", and that (2) $\top$ either denotes "false," or that it denotes true but it is now the least element (violating order-theoretic conventions), and that (3) $A \cup B = \{x : (x \in A) \wedge (x \in B)\}$, and also that (4) $\varphi \leq \psi$ iff $\{x : \varphi(x)\} \supseteq \{x : \psi(x)\}$.
Answer: "$\varphi$ implies $\psi$" means the following:

If $\varphi$ is true, then $\psi$ must be true. That is, if $\varphi=1$, then $\psi=1$ (using the notation as in the answer of @nbubis).
If $\varphi$ is false, then $\psi$ may be either false or true. That is, if $\varphi=0$, then either $\psi=0$ or $\psi=1$.

Can you now see why the implication condition is equivalent to requiring that $\varphi\leq\psi$?
Comment: I'm still not finding it intuitive though. After all, $0$ is nothing right? So we cannot prove anything from $0$. But wait; we can prove *everything* from $0$.
Comment: I'm not sure I agree with what you're saying; to me, if $\varphi$ is false, then assuming $\varphi$, we're permitted to conclude that $\psi$ is true. However, we must realize that our conclusion that $\psi$ is true only applies inside universes where $\varphi$ is true, which is to say, nowhere.
Comment: I think you are referring to a seemingly slight but very important distinction. We cannot _prove_ everything from a false statement; what _is_ true that everything is logically _consistent_ with a false statement. That is, suppose that $\varphi$ is false. Can we conclude that $\psi$ is true? Hell, no! It does mean, however, that the statement "$\varphi\Longrightarrow\psi$" is true, irrespective of whether $\psi$ is true of false!
Comment: However, the point I think I was trying to make is that $0$ is kind of reminiscent of an empty list of assumptions; from which we cannot conclude anything new. On the other hand, from $0$=false we can conclude *everything* new.
Comment: @user18921 Whenever $\varphi$ is false, the statement "_if_ $\varphi$ is true, _then_ so is $\psi$" is true. But we cannot conclude that $\psi$ is true, because $\varphi$ being false is consistent with either truth value of $\psi$. But I do see your point. If you assume a false statement, then you can arrive at another, not necessarily true, conclusion. Intuitively, if you go crazy a little bit by assuming just one false statement, then it is "logically justified" for you to go fully crazy and assume anything.
Answer: Learn how to program. Then, it will become clearer that: $$\rm{false} = 0 < 1 = \rm{true}$$
Comment: Many actual systems use 1 to signal false and 0 to signal true. Google for "negative logic"
Comment: @CarlMummert - I specifically mentioned programming - I am not aware of any major language where this "true" is not $1$.
Answer: It is the ordering by "amount of evidence for (statement)", or "range of possible situations in which (statement) is true".
If $A \to B$ then any piece of evidence for $A$ is automatically evidence for $B$.  This becomes a theorem if the evidence for $A$ is defined as the set of statements that imply $A$, and ordering of evidence is by inclusion of the sets.
If $A \to B$, then any situation where $A$ is true (considering only situations in which the logical rules leading from $A$ to $B$ hold) is one where $B$ is true.  If there is a completeness theorem for the logic then having one statement hold in a superset of the models where another holds, is equivalent to syntactic implication of one statement by the other, connecting the idea to the previous definition.
Answer: You can think of $\varphi \leq \psi$ as a sort of containment, $\varphi \subset \psi$. That is, $\varphi$ is a special case of $\psi$, so the former implies the latter.
Answer: If you can't convince that part of your brain with insight, you could try to trick it with language alone, by inserting truth-bearing adjectives into the "less than":

$\varphi$ is less evident than $\psi$
$\varphi$ is less general than $\psi$
$\varphi$ is less accommodating than $\psi$
$\varphi$ is less broadly applicable than $\psi$
$\varphi$ is less often true than $\psi$
$\varphi$ is less likely than $\psi$
$\varphi$ is less certain than $\psi$
$\varphi$ is less justifiable than $\psi$
$\varphi$ is less obvious than $\psi$

This isn't a good standalone solution, because it's blindly fighting language with language. You still need some guiding principle to help you avoid truth-forming adjectives like "strong", "strict", "interesting", "informative", or "useful". Maybe you can use one of the other answers to kick out the misleading adjectives, and then you can cement the victory by replacing it with a better adjective?
Comment: Excellent answer.
Answer: Well, weaker statements follow (logically) from stronger statements, just as later elements follow (in order) the earlier ones. In that sense, it's natural that the strongest statement should be first in the tree, while the weakest should be last.


Inference for parameters in stable distribution case

Question: I performed a fit of some SP500 returns with two heavy tailed distributions, using MATLAB.
These are like two guess about what distribution has generated the data.
This is the output

In both cases standard error for estimated parameters are reported. This sound me as suggestion to use z-test for hypothesis testing about parameters. It seems me that in t-Student case, at least for tail index greater than $2$ (finite variance), this can work. However stable distribution deal with infinite variance (exception if tail index equal to $2$). This is not a problem? ML estimator maintains asymptotic normality? If not, exist one way for parameters inference (for example $\beta$) with above output only?
Comment: I see at least two significant problems here.  First, there appear to be four questions rather than one.  Second, I can't really tell because the English is too distorted.
Comment: downvoters can explain what is wrong in the question and how to improve it?
Comment: Questions appear to be several. However it seems me easy to see that them are so strongly related that, in essence, deal with the same doubt. However I delete last part in order to accept your suggestion. About my english I'm sorry, corrections would be appreciated.
Comment: I tried to improve the english.
Answer: I got the answer. It is yes, ML estimator maintain asymptotic normality even in stable distribution case. So with output above it is easy to compute the CI and make inference about parameters in usual way.
For detail we can read Nolan (2001): https://link.springer.com/chapter/10.1007/978-1-4612-0197-7_17
especially par 3.1


How should I understand time signature?

Question: Now, I am not asking for the general answer given in band class ("The top number tells how many beats are in a measure; the bottom number tells what note gives the beat"). I'm more asking what it is and by what concept is it defined. My thoughts are:
A time signature is the "feel" of the song. For example, in most songs that are 4/4, there is a drum pattern. It starts with the bass, then the snare, then bass again and snare again. It creates a pulse; that pulse is called a "beat". If someone were to cut a song into pieces, which are, in a sense, equal, the way that makes the most sense is by dividing it into this pattern. Since the pattern consists of 4 parts, in this time, the song would have 4 beats per pattern. Other songs, however, have different patterns and those patterns are what define the measure, what gets the beat, and how many beats each measure has.
Is that correct?
Comment: While in general, you are correct, I would caution against tying the time signature too closely to any specific drum patterns. There are many different drum patterns that will fit in a given time signature (or even none, for most classical music), though the one that you listed is *very* common. You are correct to think of a beat as a pulse. The only thing I'd add is that the first beat/pulse of a measure is (usually) a stronger beat than the others. This is why you will sometimes see meter described as a hierarchy of beats: it ranks some beats as stronger, and others as weaker.
Comment: I think you need to re-think 'time sig is the feel of the song'. Often it isn't. Many different 'feels'are available within 4/4, for example. A bossa feel, a cha cha feel, even a blues feel, which could be construed as 12/8, but written in 4/4. Many more examples abound.
Comment: You have pretty much answered your own question in the second paragraph. You could make this its own answer if you wanted.
Answer: Time signatures are how we define the measures that we use to organize our music. Music is not always rigid - in fact sometimes very fluid. At the risk of getting too zen, your own concept of time relative to the music that you realize externally dictates how you perceive and apply time signatures in your music.
While most of us can agree on ranges of tempi, many of us would disagree how something should be notated. For example, a quick passage in 4/4 can be rewritten as a slower passage in 2/2. Changing our relative time perception changes our aesthetic interpretation, and therefore changes our aural experience.
Comment: and sometimes makes it easier/ harder to read/write!
Answer: Time signatures generally accomplish two things: they suggest a pattern of strong and weak pulses (and relative strong and weak pulses), and they define the notation for those pulses. Each "measure" contains one sequence of the pulse-emphasis pattern.
Simple meter
The most basic patterns are two-time (strong weak | strong weak) and three-time (strong weak weak | strong weak weak). A time signature with a 2 or 3 on top, suggests one of these patterns, unless otherwise noted (or notated). The lower number then just tells you which type of note corresponds to this basic pulse. Thus 2/2, 2/4, and 2/8 (or 3/2, 3/4, and 3/8) would all have the same pulse-emphasis pattern, just notated differently.
Compound meter
When you have an upper number that is a multiple of 2 or 3, then you get overlapping pulse-emphasis patterns. Thus in four-time, you have two strong-weak pairs in which the first is stronger than the second.

strong - weak - strong   -    weak
strong    -     weak
_____________________________________
strong - weak - semi-strong - weakest

An extensive discussion of this arose in the question Rhythmic/Metric Stress Patterns
Complex meter
When the upper number is not a multiple of two or three, then the pulse-emphasis pattern needs to be clarified. This can be done via the notation itself or via the time signature. Five-time can be notated as groupings of 2 and 3 beats, or 3 and 2 beats, or the time signature could be written as 3+2/X or 2+3/X.
Irregularly pulsed music
In John Adams's Phrygian Gates, the composer wants every note to be played with exactly equal emphasis. The score gives no time signature, and bar lines are only give to help the performer keep track of where they are in the piece.
György Ligeti, in the first of his Études pour piano, "Désordre", wants an irregular pulse pattern, both within each hand and between the two hands. To accomplish this, he uses a combination of accent markings and bar lines that don't align between the left-hand and right-hand staves.
Erik Satie eliminates both time signature and bar lines altogether in his "Gnossienne #1". Although the notation of the piece clearly suggests 4/4 time, the absence of bar lines indicates an equality of pulse, or that pulses may be applied at the performers discretion.
Comment: Re: *Phrygian Gates*, it is for this reason that I prefer Bach on the original Harpsichord: each note physically *has* to be played with the same dynamic (or muted). That's how Bach intended it; to my ear he creates "illusory" dynamics that emerge from the tonal relationships. Playing *Goldberg Variations* on a piano somewhat decimates the effect.

Also, Ligeti's music is incredible!

How should I understand time signature?


Windows File Sharing Orphaned File Locks

Question: Over the past few weeks the company I work for has been having issues on their server wherein a file gets locked by something, and can't be unlocked. These files are almost always files that are being actively accessed over Windows file sharing. I've downloaded the popular Unlocker program, but that is unable to find any lock on the file. openfiles.exe (or System Tools > Shared Folders > Open Files) does not show the file as being open by anything. Yet I'm unable to open it in anything, including notepad - the system gives me a permission denied error even when accessing the file as the local system administrator. The problem always goes away when the server is rebooted.
To make matters worse, I've also been unable to reproduce this error at all. It's frequency is anywhere from daily to a week of working perfectly fine. When the problem does happen, I have very little time to investigate it, because nine times out of ten the problem makes our production systems completely nonfunctional, and management wants the server rebooted.
The problem is also not limited to a single application. The majority of the file sharing traffic is in our production management software, Globalshop, so the problem usually manifests itself somewhere in there, however the most recent occurrence was in a Microsoft Access database completely separate from anything Globalshop.
Has anyone seen anything like this? Any idea what could cause it? Let me know if there's any more information you need.
We're currently running Windows Server 2003 Standard Edition.
[edit] I've tried checking permissions, but I'm disallowed access to those as well on the offending file. I can't open, move, delete, rename or even copy the file.
[edit2] I've managed to isolate two offending files. As long as no other production-interfering problems crop up, I've been authorized by management to keep the server online for the rest of the day to test them.
[edit3] Brettski, in comments, suggested that I look at the file permissions. I've taken a screenshot of the properties window of one of the offending files. As you can see, there are no permissions available. http://i43.tinypic.com/24xgpe8.png (This is opened as the system administrator with full access rights.)
Comment: Does System Tools > Shared Folders > Open Files show the files as being open by anyone?
Comment: When you cannot access the file, have you checked the file permissions, have they changed in any way.  I know you said it clears itself when rebooting, but thought it's worth a check.
Comment: The permissions I assume are fine, but I'm disallowed access to those as well on the offending file, so I can't say.
Comment: When on the server as local/domain admin you cannot view the access rights to the file?  Normally if you can see the file (file scan) you can see it's access rights.  Another symptom.
Comment: Hmm. I'll take a closer look at the file properties next time it happens.
Comment: No. The file doesn't appear there, or in the output of openfiles.exe
Comment: Brettski: I've updated the initial question with a link to the properties window for one of the offending files.
Comment: Just to be sure, you are opening the file from the server console (or remote desktop to server)?
Comment: I've tried both locally on the server, and over remote desktop, with the same results on both.
Answer: Grab Handle.exe (http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx) and, on the server computer, run a "handle -a" redirecting the output to a text file. Search that for the affected filename. That should at least tell you what process on the server computer has an open handle to the file. I'd be interested to know what process has a handle to it. (I'm wondering about anti-virus software as a possibility...)
My condolences for having to deal with GlobalShop, BTW.
Edit:
McAfee VirusScan 8, eh? Have a look at this: https://kc.mcafee.com/corporate/index?page=content&id=KB52156
It refers to Microsoft Office files, but it sounds suspiciously like it could affect any type of file. See also:
http://forums.mcafeehelp.com/showthread.php?t=223545
http://www.tek-tips.com/viewthread.cfm?qid=1453943&page=1
https://web.archive.org/web/1/http://techrepublic%2ecom%2ecom/5208-6230-0.html?forumID=101&threadID=207897&messageID=2632853
Comment: This is my favorite part - no matter what tool I use to view open files, the offending file is not there. The filename is RQT20TX099.TXT, which appears nowhere in the output of handle.exe or openfiles.exe, and is nowhere in System Tools > Shared Folders > Open Files. As far as I can tell, it's really actually not open.

And I thank you for your condolences. :)
Comment: And, the server is running McAfee VirusScan Enterprise 8.
Comment: That seems really promising. The problem seems to be in VirusScan 8.0, which is the version we have. I'll try upgrading. (Unfortunately I have no way to assert that it fixed the problem, as I haven't figured out how to reliably reproduce it yet.)
Comment: Intermittent problems piss me off!  *smile*  Keep us appraised. If nothing else, if after the upgrade you can run for a multiple of the time in which the problem was happening previously you can probably be fairly confident that you've squashed the bug.
Comment: You may be interested to know that today we found out (the hard way) that our automatic backup software stopped making nightly backups at precisely the same day that this issue started.
Answer: Procmon might be your best solution here as it is able to log what processes are using what files.  Even if the file isn't showing up in openfiles procmon will log who opened it.  Antivirus software is the usual culprit in these cases.
Comment: thanks for the tip. I have similar issues on w2012 file server.
Answer: I have been having a similar problem on our file server (Windows Storage Server 2003 R2 x64).  Only small temporary files (usually Access .ldb "lock" files, but also temp files used for various processes), no pattern on location or size or name or type.  Files were locked with no access to permissions; unlocker programs (I was using EMCO UnLock IT, to which I will give a thumbs-up in passing) did not see any programs holding the files as locked.  Rebooting always fixed the problem, but that was a major PITA with everyone having some files in use on that particular server.
Based on comments here, I turned off our AV software on that server.  Without rebooting, the file that was untouchable a moment ago vanished (it was a temp file that should have been deleted anyway, so this was A Good Thing).
AV software is CA eTrust Antivirus v. 7.1.  I'm guessing (with the aid of hindsight) that Old Software + x64 OS = Occasional Bad Things.  :-)
My thanks to Sean and Evan for the discussion.
Answer: Unlocker seems to have potential.  I haven't had a chance to try it yet though, so let me know how it works.
Comment: As I said in the initial question, I've already tried it. Unlocker can't find any locks on the file to release.
Answer: This is a very old topic, yes. But the reason and solution is detailed in this page about Opportunistic File Locking behavior in Windows. See the content under the heading "MS Windows Oplocks and Caching Controls" towards the end of the page.
Link: https://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/locking.html
The opening paragraph is the clue to why this is relevant (almost exactly what the OP faced):

There is a known issue when running applications (like Norton Antivirus) on a Windows 2000/ XP workstation computer that can affect any application attempting to access shared database files across a network. This is a result of a default setting configured in the Windows 2000/XP operating system. When a workstation attempts to access shared data files located on another Windows 2000/XP computer, the Windows 2000/XP operating system will attempt to increase performance by locking the files and caching information locally. When this occurs, the application is unable to properly function, which results in an "Access Denied" error message being displayed during network operations.

Hope it helps.


Updating MySQL trigger with additional Query and Insertion Logic

Question: I have two tables in a MySQL 5.7.28 database.  One table with submitted XML data from a form dumped into a single column called xmlData
The second is a table with serves as a datasource for a Datatables based JS site, called Employees
When the xml data is first submitted to the xmlData table, I use the MySQL trigger below to parse and insert the data into Employees.
use test;

DELIMITER $$
DROP TRIGGER IF EXISTS test.Update_xmlData$$
CREATE TRIGGER test.Update_xmlData AFTER INSERT ON xmlData

FOR EACH ROW BEGIN

replace INTO employees (first_name, last_name, startTime, endtime, date)

select ExtractValue(xmlData, '/Data/Employee/first_name') as first_name,
ExtractValue(xmlData, '/Data/Employee/last_name') as last_name,
ExtractValue(xmlData, '/Data/Employee/StartTime') as startTime,
ExtractValue(xmlData, '/Data/Employee/EndTime') as endtime,
ExtractValue(xmlData, '/Data/Employee/date') as date
from xmlData;

END

The output of which looks like this
---------------------------------------------------------------------
first_name |  last_name   |   startTime   |   endTime   |     Date
---------------------------------------------------------------------
  Luke     |  Skywalker   |   08:00       |    15:00    |  2019-12-05
----------------------------------------------------------------------
  Santa    |   Clause     |   08:00       |    14:00    |  2019-12-25
----------------------------------------------------------------------

This trigger works fine and inserts the data properly.  The complication is that there maybe multiple start and endtimes in the submitted xmlData row.  One set for each day of the week.
For the time being, I'd like to query the submitted XML and persist these values in the Employees table as separate rows.  For example, if there are Monday, Tuesday and Wednesday start/end times
the inserted data would look like this:
---------------------------------------------------------------------
first_name |  last_name   |   startTime   |   endTime   |     Date
---------------------------------------------------------------------
  Luke     |  Skywalker   |   08:00       |    15:00    |  2019-12-05
----------------------------------------------------------------------
  Luke     |  Skywalker   |   09:00       |    17:45    |  2019-12-06
----------------------------------------------------------------------
  Luke     |  Skywalker   |   06:00       |    18:00    |  2019-12-07
----------------------------------------------------------------------
  Santa    |   Clause     |   08:00       |    15:00    |  2019-12-25
----------------------------------------------------------------------

What would be the best approach for updating the trigger to insert new rows IF there are existing StartTime/EndTime for additional days of the week?  Is 1 trigger even still viable at this point?
In plain English, I was thinking something along the lines of :
IF TuesdayStartTime and TuesdayEndTime EXISTS THEN insert into Employees another row retaining the same name field values, increment date by 1 day,
IF WednesdayStartTime and WednesdayEndTime EXISTS THEN insert into EMployees another row retaining the same name field values and increment date by 2 days

Submitted XML that is being queried and inserted into employees table:
XML Sample Source Schwartz 08:00 09:00 11:0018:0020191221051312
Comment: Can you loop over all the elements in the XML data and insert them all?
Comment: What is the unique key of the `employees` table that you're using with `REPLACE INTO`?
Comment: What do you mean by start times for different days of the week? Isn't the day of week determined by the date field? Can you show what the XML looks like?
Comment: Or is the date just the date of Monday?
Comment: Inserting them all isn't necessary at this point and there's ~ 120+ of xml elements.  The unique key is 'id' and it's autogenerated.
Comment: I'm pulling the date field from a "submitted on" date.  To simplify things I'm using the "submitted on date" as the start date.                                                                                The forms looks something like this:
Week 1
Sunday Start Time  _____              Sunday End Time _______
Monday Start Time _____.             Monday End Time _______
Tuesday Start Time ______            Tuesday End The _________

So on and so forth
Comment: Put the XML in the question.
Comment: If you're using `REPLACE INTO` you need another unique key, so it knows which rows to update.
Comment: If none of the columns you're replacing are unique, it will just insert a new row instead of replacing.
Comment: Inserted XML into question.  So I created a Unique index on the employees table and created a second trigger to run to run and insert a different query for the subsequent dates and that seems to work except I need to increment the date field by +1 day for Mondays, +2 Days for Tuesdays, etc.  I tried set ExtractValue(xmlData, '/Data/Employee/date') as date; I know there's an date add function which looks like DATE_ADD(date, INTERVAL 2 DAY).  My remaining question would be how to insert that function within the trigger after the ExtractValue Statement...
Comment: What you put in the question is just plain text, not XML. Where are the multiple entries for the same name with different days?
Comment: Anyway, what you need to do is write a loop that increments a variable from 0 to 6. For each value, look for the corresponding day of the week in the XML, and if you find it update the corresponding row in the table.
Answer: As Barmar described I can create a loop.
I also found a less elegant way that works by extracting the submitted date and using multiple triggers for each day of the week:
DATE_ADD(ExtractValue(xmlData, '/Data/Employee/date'), interval 1 Day) as date for trigger_Monday
DATE_ADD(ExtractValue(xmlData, '/Data/Employee/date'), interval 2 Day) as date for trigger_Tuesday
Creating an Index of type Unique on the Employees table prevents duplicates.


Page Layout Scrolls Off The Screen

Question: Having a problem with this site, http://www.keefebartels.com/. The page looks OK but you'll notice you can scroll to the right. Not sure what's causing this. I thought it would be a weird  issue that I'm missing. Any ideas?
Comment: Please add meaningful code and a problem description here. Don't just link to the site
that needs fixing - otherwise, this question will lose any value to future visitors once
the problem is solved or if the site you're linking to is inaccessible. Posting a
[Minimal, Complete, and Verifiable example (MCVE)](http://stackoverflow.com/help/mcve) that
demonstrates your problem would help you get better answers. For more info, see
[Something on my web site doesn't work. Can I just paste a link to it?](http://meta.stackexchange.com/questions/125997/)
Thanks!
Comment: You have some elements with a defined width in pixel (I found, for instance, 1300 and 2000). However, as suggested by @j08691 , you need to edit your post, since its quality is too low right now
Answer: The issue is in the CSS associated with the following code:

    Injury Claim Calculator

It shows that the calc class is getting the following property.  This is causing for the link to be placed 900px to the right and therefore causing you to be able to scroll to the right.
right: -900px;

Removing the above code from the CSS will fix the site.
Answer: Go to your style.css file, find .calc class and remove right:-900px;
Fixed!!
Answer: Add overflow:hidden to the .textwidget element in the sidebar; it's child element .calc is positioned relative and as a result it's flying off the screen, forcing the scrollbar to appear.
Comment: What about "Injury Claim Calclator" link.  Don't you want that to be visible on the page?  This solution hides in from being visible on the page.

Page Layout Scrolls Off The Screen


Filtrar com select em php

Question: tenho este código com os 3 selects para filtrar uma consulta:
<form class="shadowbox6" action="" method="post">
    Estado Encomenda
        <select name="pesquisar">
            <option></option>
            <?php
                $sql = "SELECT * FROM centrodb.EstadoEncomendas";
                $qr = mysqli_query($conn, $sql);
                while($ln = mysqli_fetch_assoc($qr)){
                    echo '<option value="'.$ln['Estado'].'"> '.$ln['Estado'].'</option>';
                }
            ?>
        </select>
        Valência
        <select name="pesquisar">
            <option></option>
            <?php
                $sql = "SELECT * FROM centrodb.Destinos WHERE Id IN (1,2,3)";
                $qr = mysqli_query($conn, $sql);
                while($ln = mysqli_fetch_assoc($qr)){
                    echo '<option value="'.$ln['Destino'].'"> '.$ln['Destino'].'</option>';
                }
            ?>
        </select>
        Requerente
        <select name="pesquisar">
            <option></option>
            <?php
                $sql = "SELECT * FROM centrodb.Requerentes WHERE Id IN (1,2,4,5,8)";
                $qr = mysqli_query($conn, $sql);
                while($ln = mysqli_fetch_assoc($qr)){
                    echo '<option value="'.$ln['Requerente'].'"> '.$ln['Requerente'].'</option>';
                }
            ?>
        </select>
        <button class="botao" type="submit">Consultar</button>
</form>

if(isset($_POST['pesquisar']))){
    $pesquisar = $_POST['pesquisar'];

$result_cursos = "SELECT IdRequisicao,
       CASE WHEN centrodb.EncomendasGerais.Estado IN (1,2,6) THEN DATE(DataEncomenda)
       WHEN centrodb.EncomendasGerais.Estado IN (3,4,5,7) THEN DataAprovacao END AS `Data`,
       IdTipoProduto,
       IdProduto,
       Quantidade,
       IdRequerente,
       IdDestino,
       Fornecedor,
       centrodb.EstadoEncomendas.Estado,
       Preco

FROM centrodb.EncomendasGerais LEFT OUTER JOIN centrodb.EstadoEncomendas

on centrodb.EstadoEncomendas.Id = centrodb.EncomendasGerais.Estado

WHERE centrodb.EstadoEncomendas.Estado LIKE '%$pesquisar%' AND IdDestino LIKE '%$pesquisar%' AND IdRequerente LIKE '%$pesquisar%'
...
}

Se utilizar só o primeiro select funciona bem o filtro, se adicionar as 3 possibilidades de filtro já não funciona.
Comment: Coloque os selects com names diferentes, e na hora de fazer a consulta, trate se recebeu algum post vindo de cada select antes de adicioná-lo na query.
Answer: O name dos campos selects é o mesmo, então o ultimo exibido na tela e preenchido é o que fica guardado no $_POST["pesquisar"], por isso não esta dando certo. Se vc printar a sua query vai vai perceber que os três parâmetros ficaram com o mesmo valor.
Tente usar names diferentes nos selects e criar três variáveis de pesquisa, uma para cada select. Algo como :
<select name="pesquisar_estado">
<select name="pesquisar_destino">
<select name="pesquisar_requerente">

e no php vc recebe cada select em uma variavel
if(isset($_POST['pesquisar_estado']))){
   $pesquisar_requerente = $_POST['pesquisar_requerente'];
}
if(isset($_POST['pesquisar_destino']))){
   $pesquisar_destino = $_POST['pesquisar_destino'];
}
if(isset($_POST['pesquisar_requerente']))){
   $pesquisar_requerente = $_POST['pesquisar_requerente'];
}

Filtrar com select em php


Re-creating complex CSS footer layout in Drupal

Question: I've been given some HTML & CSS files by our university web designer and need to replicate essentially the same layout into the library website I'm creating in Drupal. The footer (pleased see attached link) has been the biggest hurdle so far. With this type of column-based inline layout consisting of menus (which I haven't created as menus yet), should I be creating new regions in my .info file to handle each menu? Also with the university address info. and icons, should this be another region or should I add custom variables and HTML so it is just part of the main footer region? Or is there a way using Blocks, Panels or another module to create this layout more efficiently?
One last thing-as you can see the columns have three headings (Who Are You?, Quicklinks, and Admissions) so I plan to create a menu with each name as title. What's the best strategy to deal with the overflow of menu items over more than one column without having to create six separate inline regions for layout purposes?
Thanks for any assistance, guidance, or suggestions. This site has been an invaluable resource in learning Drupal over the past few months and I've learned a lot from all your posts, responses & comments to each other.
The footer design:
footer http://dl.dropbox.com/u/664958/footer.png
Answer: I'd set up one region for those menus, in that region have 3 x menu blocks (http://drupal.org/project/menu_block), 1) Who Are You, 2) Quicklinks 3) Admissions.
CSS will be your friend to get the required layouts.
The "Who Are You" menu should be easy, float the menu block left and fix the width. The same for the "Admissions" menu.
The middle menu will be similar but all you need to do is have a wider fixed width menu block, fix the width of the menu items and float them left. Then you'll have to order the menu items to make them appear in the correct columns.
The text below the menus should simply be 2-3 more standard text blocks just styled appropriately.
I hope this makes sense. I'll be interested to see how other developers would attack this.
Cheers.
Comment: I was just going to suggest that module. Having 1 big list of links it's easy to drag&drop and edit. Then split them by by depth with menu_block.
Answer: The Skinr module can help with this kind of thing: http://fusiondrupalthemes.com/support/documentation/layout/adding-menu-your-sites-footer
If you are using Drupal 6, I would try it out. It is not quite ready for 7, but it is probably worth looking at anyway. There are a lot of other things that it can make easier, and many base themes have some built in support for it.
Comment: I've thought about using Skinr because, while someone else created the CSS, trying to map or cross-walk the style info (divs, spans, classes, IDs, et. al) from one of the HTML files to a template like Fusion or Zen is another daunting task I have to face.
Comment: If you are thinking of using Fusion, you really should try Skinr out, the built in Skinr styles will get you part of the way there.


How to make my user notifications module notify node authors about new comments?

Question: I need to send a notification to the article owner when some user comments on the review added to an article.
But in the Rules module, while adding a Rules Action, there is this action: 'Send notification to user when flag is applied' (part of a custom module I inherited from a prior mantainer of this site). With this action, notification is only sent to the reviewer, not the article owner.
Can anyone help to get this to work? Or is there another way to make this work without the custom module I'm struggling with?
Here is my rule:
{ "rules_send_notification_when_commented_on_article_listing" : {
    "LABEL" : "send notification when commented on article\/listing",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "user_notifications", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_is_of_bundle" : {
          "entity" : [ "comment" ],
          "type" : "comment",
          "bundle" : { "value" : {
              "comment_node_article" : "comment_node_article",
              "comment_node_page" : "comment_node_page",
              "comment_node_comment" : "comment_node_comment",
              "comment_node_company" : "comment_node_company",
              "comment_node_review" : "comment_node_review"
            }
          }
        }
      },
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "user_notifications_action_send_notification_flag" : {
          "flag_as_flag" : "commented",
          "content" : [ "comment:node" ],
          "message" : "commeted on ",
          "heading" : "d"
        }
      }
    ]
  }
}

Comment: Comments have been removed. Please don't use them for extended discussion; instead, include the relevant part in the question.
Answer: As per the "Or is there another way to make this work without the custom module I'm struggling with?" in your question, IMO the answer is yes. Read on for more details about how to "send a notification to the article owner when some user comments on the review added to an article." (as in your question).
Have a look at this, rather basic, rule (in Rules export format):
{ "rules_notify_node_author_about_new_comment" : {
    "LABEL" : "Notify node author about new comment",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "comment:node:author" ], "value" : [ "comment:author" ] } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "comment:node:author:mail" ],
          "subject" : "A new comment was posted to the node you authored",
          "message" : "A new comment was posted, you can find it at [comment:url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Use the Rule UI to import it in your own environment. Some more details about this rule:

Event: After saving a new comment.
Condition: Check that the user who posted the comment is different from the node author (I'd think it doesn't make sense to notify the node author of comments posted by the node author, right?).
Action: Send an eMail to the node author, with a link to the comment that got posted.

Feel free to add any rules conditions that may fit to further improve the above prototype, to fit your actual requirements.
Note that the above rule doesn't depend on any other module, though you could make it way more sophisticated if you'd also get the Message module involved (eg to create a log file of all such eMails ever being produced, if that's what you'd want to do).
BTW: no need for custom code ...
Comment: Thanks for your effort @Pierre.Vriens, but I think you are not yet clarified about the 'notification' part. By notification, I meant, notifications as that  in face book and all, which are in the site itself. Also in your rule, you have set the to address:[comment:node:author:mail], which I have tried using custom code. It will sent mail only to the reviewer, not the owner,
Comment: @bincy I bet you are not really familiar yet with how things work on this site (eg: because you have not earned the "informed" badge yet, as shown in your profile). So please have a look at [this](http://drupal.stackexchange.com/help/someone-answers), especially the bold phrase in the last paragraph. Also: (1) the "notification" requirement you now added in this comment, should have been included in your actual question, how about you make that a followup question (with link to this one)? (2) "We" cannot help here with debugging custom code not shown (I'm pretty sure about that token).
Comment: Solved it by writing a query to directly insert the notification into the table.
Comment: @bincy merci for the update. Maybe you should post your own answer with the code/query included, so that others can learn from your own answer, and you can mark your question as solved (by marking your own answer as accepted)? That way the question wil also no longer show up as unanswered.


A container with O(1) insertion (amortized) and O(n) iteration

Question: I'm looking for a set-like container class that has these basic properties:

has amortized O(1) insertion time, duplicate inserts are ignored
has O(n) iteration time (specifically O(capacity) is not acceptable)
reuses memory / only allocates when it exceeds current capacity

The use-case is that I have a larger container of objects. During each loop I'll add a subset of those objects to this new container. This subset can be from 1-5 objects or up to 10% of the entire set. I then iterate of the objects in this new set. Each loop the object will be cleared and the processed started again.
My original approach used a invasive boolean on the objects indicating if it belonged to this new set. Thus insertion was true constant time, and it used no new memory. However iteration was sub-optimal.
I've tried a boost::unordered_set and get worse performance than my original approach. Presumably since, as hash map, it fails to meet Point #2.
Point #3 is relevant since I'm coding at a latency level where the cost of memory allocation is very significant. Thus it is extremely unlikely that a container with continuous allocation will perform well.
Comment: @aschepler, pretty much all hash maps achieve that (amortized at least).
Comment: I don't think O(1) insertion and duplicate detection are both possible at once.
Comment: O( capacity ) is usually O( n ) no?  Unless you're using some sort of crazy data structure..
Comment: You could just use a generic hash set and use specialized memory management, either for the whole program or for the specific hash set.  This is not an easy thing to do, but if your memory allocation costs are abnormally high, the standard memory allocation algorithm may not be appropriate.
Comment: @edA-qamort-ora-y: do you have a good hash function on those elements ? Specifically I am thinking about OpenAddressing to implement hash tables, but to meet the `O(1)` insertion you need to bound the number of tries to find a slot.
Comment: @Timmy: no, `vector` or `deque` will reserve memory in chunks, so the capacity is usually a bit larger. In exchange, you don't need to allocate memory at each insertion, so you're faster.
Comment: @MatthieuM., I don't really have a good hash, but a normal mod might be okay (they are essentially counters starting at a series of fixed intervals).
Answer: Use your first approach to detect whether the element is already in the set (hash map). And put it also in a list for iterating..
Comment: note that you will also have to directly connect from each element in the set to the element in the list to allow removal of elements [if it is a requirement].
Comment: @amit, strangely enough, the removal of an element has no cost restriction.  Usually `clear` will just be called, which is of course expected to be constant time.
Comment: @edA-qamort-ora-y: If no deletions are expected, then I think this approach should do. If deletions are needed, you should reference between elements in the 2 data structures.
Comment: @edA-qamort-ora-y: `clear` is NOT constant time, it calls the destructor of each object! Furthermore, with a `list`, you need to free each node of the list individually, and even if you use a `deque` you will still have this issue (though not as much).
Comment: @MatthieuM.: does this even matter? maybe he has built his own mem manager where he can throw away all his memory in no time...
Comment: @MatthieuM., I should mention my objects are fundamental data types (a pointer in this case) so there is no destructor cost.
Comment: @duedl0r: it does matter, whatever the memory management, the implementation of `vector` will call the destructors. It is a quality of implementation whether or not this is optimized out in the no-destructor case (note that C++11 provides the a trait to detect this). Anyway, if you use a `deque`, you still have to `delete` the chunks you had grabbed and no longer use on a `clear`, which is `O(N)`. As far as I know, `vector` is the only STL container which may have a `O(1)` `clear`.
Answer: You can use a linked hash set. LinkedHashSet in java. I don't know if there exist a library in c++ that implements it, but the idea is simple: have a hash set of entrees, and let the entrees also form a linked list.
Iteration is on the linked list, and insertions are made from the hash set. Note that this approach allows insertions to the list only on its back.
Comment: Yes, that is kind of the idea. Thanks.
Answer: Try Emde Boas tree. It could fit your purposes:

Insertion O(log(log(n))),
Iteration O(log(log(n))),
Memory... Well, just read the link provided...
Comment: Thanks, I'll look at it more. It may not work since my key sizes are relative large (64-bits) compared to the number of elements (a few hundred at most).
Answer: You can improve your method by adding a linked list.
There will be a linked list of the pointers (or whatever identifier suitable) to the inserted objects. In addition leave the boolean variable inside each your object, to know if it's already inserted to the list.
Comment: actually, not exactly, `list` is generic while linked list precises an implementation. Given the tight memory constraints (point 3), a linked list does not seem appropriate, unless you consider that the capacity is always stricly equal to the size...
Comment: I didn't understand a word from what you said. I didn't mean one should use an `std::list` if this is the point. Nevermind...