Conditional Variance

Question: X is a random variable with mean 100 and standard deviation 30. Y is a random variable with mean of 50 and standard deviation of 25. The correlation between X and Y is 0.5. What is Var(Y|X)?
Comment: Perhaps you are missing some assumption - eg. X and Y are jointly normal ? Besides, I guess that it's `the correllation coefficient` which is 0.5
Answer: There is no unique answer to your question without some additional information on the joint distribution of $(X,Y)$. Here are two examples of couples $(X,Y)$ which both fulfill all the conditions in your post and such that $\mathrm{Var}(Y|X)$ is different.
Your hypothesis are that $E(X)=x$, $\mathrm{Var}(X)=u$, $E(Y)=y$, $\mathrm{Var}(Y)=v$ and $\mathrm{Corr}(X,Y)=c$, with $x=100$, $u=900$, $y=50$, $v=625$ and $c=1/2$. In both situations, an auxiliary random variable $Z$ is introduced, independent on $X$ and such that $E(Z)=z$ and $\mathrm{Var}(Z)=w$, where the values of $z$ and $w$ will be specified later on.
First example: Assume that $Y=aX+Z$ for a given $a$, then $y=ax+z$, $v=a^2u+w$ and $c=a\sqrt{u/v}$. The third equation yields $a=c\sqrt{v/u}$, the second one yields $w=(1-c^2)v$, the first one yields $z=y-cx\sqrt{v/u}$ and this $(a,z,w)$ yields an admissible couple $(X,Y)$. Furthermore,
$$
\mathrm{Var}(Y|X)=\mathrm{Var}(Z)=w=(1-c^2)v.
$$
Second example: Let $S$ denote a random variable, independent on $X$ and $Z$, with $P(S=1)=p$ and $P(S=0)=q=1-p$. Assume that $Y=SX+(1-S)Z$. In words, $Y=X$ or $Y=Z$ with probability $p$ and $q$ respectively. Then $y=px+qz$, $v=pu+qw$ and $c=p\sqrt{u/v}$. Hence $p=c\sqrt{v/u}$ is imposed, $w=(v-pu)/q$ as well (and $w>0$ for the suggested numerical values) and $z=(y-px)/q$ as well. Furthermore,
$$
\mathrm{Var}(Y|X)=pq(X-z)^2+qw.
$$
Answer: Note that  $$\text{Var}(Y) = E(\text{Var}(Y|X))+ \text{Var}(E(Y|X))$$ so that $$E(\text{Var}(Y|X)) = \text{Var}(Y)-\text{Var}(E(Y|X))$$
Comment: PEV: I would appreciate if you could make precise the ways in which your post is relevant to the question asked.
Comment: I don't know what E[y|x] is. How do I find that?

Conditional Variance


Função que retorna vetor

Question: Como retornar um vetor dentro de uma função? E como eu chamo ela no main?
Esse return no caso: (return vetor;)
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

float UK (int mat[4][4], float w[3]){
float *vetor[4];
float res = 0;

    for(int l=0; l<4; l++){
      //printf("\n");
       float soma = 0;
        for(int c=0; c<3; c++){
          //printf("%tfd ", mat[l][c]);

          res = mat[l][c] * w[c];
          printf("Resultado: %f\n", res);

          soma = soma + res;

         }

         *vetor[l] = soma;
         printf("Vetor: %f\n", vetor[l]);
     }

    return vetor;
}

float *Limiar(float vet[]){

for(int c=0; c<4; c++){
    if(vet[c] >= 0)
    vet[c] == 1.0;
    else
    vet[c] == 0.0;
}
printf("Yl: %d", vet);
return vet;
}

float Delta(){

}

int main () {
int mat[4][4];
float w[3];

mat[0][0] = -1;
mat[0][1] = 0;
mat[0][2] = 0;
mat[0][3] = 0;
mat[1][0] = -1;
mat[1][1] = 0;
mat[1][2] = 1;
mat[1][3] = 0;
mat[2][0] = -1;
mat[2][1] = 1;
mat[2][2] = 0;
mat[2][3] = 0;
mat[3][0] = -1;
mat[3][1] = 1;
mat[3][2] = 1;
mat[3][3] = 1;

w[0] = 0.2;
w[1] = 0.2;
w[2] = 0.2;

Limiar(UK(mat, w));
return 0;
}

Comment: Não pode retornar um vetor criado estaticamente dentro de uma função. Utilizar esse ponteiro fora da função representa comportamento indefinido
Comment: Poderia usar passagem por referencia talvez
Comment: Não entendi muito bem, poderia exemplificar?
Comment: vetor deixará de existir quando a função for encerrada, como uma variável local comum
Comment: Como que eu chamo no main?
Comment: ou usar *float \*vetor = (float\*)malloc(sizeof(float)\*3)*, por exemplo para criar um ponteiro com 3 posições
Answer: Problema
Vamos começar por perceber o problema:
float UK (int mat[4][4], float w[3]) {
    float *vetor[4];
    ... //instruções que não são relevantes para perceber o problema
    return vetor;
}

Aqui tem já varios problemas, olhando só para estas linhas de código.

O tipo de vetor é float** pois é um vetor de ponteiros para float. Logo o tipo de retorno da função deveria ser float**:
float** UK (int mat[4][4], float w[3]) {
//---^

Se criou um array estatico dentro da função:
float *vetor[4];

Não pode retorna-lo e utilizar fora dela.

Mas porquê ?

Este array foi alocado no stack, no espaço que foi atribuído à função e todas as suas variáveis. Por este motivo quando a função termina esse espaço é marcado como livre, podendo os valores que lá estão serem eliminados a qualquer momento. Isto implica que qualquer acesso a um desses ponteiros vai gerar comportamento indefinido e mais tarde ou mais cedo um Segmentation Fault.

Soluções

Alocar o array no heap através de malloc:
float ** vetor = malloc(sizeof(float*) * 4);

Tenha cuidado com esta aproximação. Embora seja util e necessária em vários casos, tem mais implicações do que parece. Não só lhe dá a si a responsabilidade de ter de liberar a memória alocada, quando já não precisar dela chamando free, como lhe vai potencialmente fragmentar mais a memoria.
Passar o array já alocado para os resultados. Neste cenário a função recebe como parâmetro o o array a processar e aquele onde é colocado o resultado:
void UK (int mat[4][4], float w[3], float *vetor[4]) {
    //              array de resultado aqui ----^
    //sem retorno
}

Neste cenário a chamada do main, considerando apenas esta função em isolado seria assim:
float *vetor[4];
UK(mat, w, vetor);

Esta solução torna a gestão de memória mais fácil, mas em contrapartida força quem chama a ter de definir o tamanho dos resultados de forma determinística.
Comment: Fiz como está na explicação, mas apareceu esse problema:
[Error] declaration of 'float** vetor' shadows a parameter
Comment: @HeloisaDiniz É porque não aplicou corretamente. Suspeito que esteja a aplicar a versão com `malloc`. Se for esse o caso a instrução que eu dei substitui a antiga que era `float *vetor[4];`, assumindo que corrige também o tipo de retorno
Comment: Não consegui...
Answer: Montei um exemplo de como você pode manipular seu vetor na função espero ajudar.
#include <stdio.h>
#include <stdlib.h>

void alterarVetor(float vetor[], int tamanho){
    float *ponteiro;
    float *ultimoVetor = vetor+tamanho;

     for (ponteiro = vetor; ponteiro < ultimoVetor; ponteiro++) {
     *ponteiro = 6;
   }

 }

 int main(int argc, char const *argv[]) {
 float vetorOrigem[4]={0.2,0.1,0.0,0.1};

  alterarVetor(vetorOrigem, 4);

  for (int i = 0; i < 4; i++) {
  printf("Vetor: %0.1f ", vetorOrigem[i]);
 }
 return 0;
 }

Comment: Muito obrigado, agora eu consegui :D

Função que retorna vetor


How to make a relation between nodes in drupal 7?

Question: I need to create a relation between to nodes in drupal 7 without taxonomy.. because I don't have taxonomy option for drealty_listing.. And after I need to create a view regarding these relation.
Comment: What kind of relationship are you talking about? Have you looked at the [Entity Reference module](https://www.drupal.org/project/entityreference)? I think we need more information about your problem to be able to help you.
Answer: Entity Reference module works well. But If you need to create a view, you may use Entity View Attachment module. This module attaches a view to a node.


Only create taxonomy terms on node approval?

Question: Right now nodes on my site are unpublished by default because I want to manually approve user submitted content. How can I make it so that user submitted taxonomy terms are not created until I manually approve the corresponding node?
Answer: As far as I can see, this would require a custom module. You would have to do something like this (tailor to your needs; I don't know if you're using publishing status to represent approval status).
    <?php
      function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
        switch ($op) {
          case 'presave':
            if (!empty($node->taxonomy) && $node->status == 0) {
              // Write some logic to save the data to your module's DB table, e.g.
              // _mymodule_get_taxonomy_temp() would contain a database query or
              // something to get the record.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              $record_exists = !empty($record);
              $taxonomy_temp = ($record ? $record : new stdClass());
              $taxonomy_temp->taxonomy = $node->taxonomy;
              $taxonomy_temp->nid = $node->nid;
              if ($record_exists === FALSE) {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp),
              }
              else {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp, 'nid'),
              }
              unset($node->taxonomy);
            }
            elseif (!empty($node->taxonomy_temp && $node->status == 1)) {
              // Retrieve the saved taxonomy and put it back into the node.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              // We append it to any changes made during the approval process.
              $node->taxonomy = array_merge($node->taxonomy, $record->taxonomy);
              // Clean up the database record
              _mymodule_delete_taxonomy_temp($node->nid);
            }
            break;
        }
      }
    ?>

Note that this is strictly sample code. You might want to retrieve the terms using hook_form_alter instead and show them in the tags box as if they had been added. In any case, the key is not to have them in $node when taxonomy_nodeapi() runs and saves them.
Answer: If you are OK with the taxonomy terms existing for a brief second then you can move them to a vocabulary otherwise unused on hook_nodeapi insert and, upon hook_nodeapi update if status flips from 0 to 1 then move them back to the vocabulary attached to the node.
  function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    switch ($op) {
      case 'insert':
        $tids = array_keys($node->taxonomy);
        $placeholders = db_placeholders($tids);
        db_query("UPDATE {term_data} SET vid = 654321 WHERE tid IN ($placeholders)", $tids);
        break;
      case 'update':
        if ($node->status) {
          db_query("UPDATE {term_data} SET vid = 23 WHERE tid IN (SELECT tid FROM {term_node} WHERE nid = %d)", $nid);
        }
 }

Where 654321 is a vocabulary you created but didnt assign node types to it and 23 is the vocabulary your nodes can use. This way the terms get created but other nodes cant use 'em, an appropriate View wouldn't see them etc. It's a hack. But a very effective hack.
Comment: That didn't work
Comment: Works if I use $tids = array_keys(taxonomy_node_get_terms($node));
Comment: Did you try to debug the $node object? Theoretically it has the taxonomy terms on it but I must admit I've forgotten the structure of it in D6.
Comment: I tried debugging the node object. It has the terms name as a string but no tid.
Comment: Also change $nid to $node->nid and it works perfectly


Mediation: a & b path positive & significant, insignificant total effect and NEGATIVE direct effect

Question: I am testing a mediation model for a research question using PROCESS in SPSS. While I realize Baron and Kenny (1986) would not test this model, I have read quite a bit about it not being necessary for there to be a total effect between x and y.
Where I am confused: How can I make sense of the two positive paths, with a significant negative direct effect?
Answer: This seems entirely plausible.
If the direct effect of $X$ on $Y$ is negative, while the mediated effect is positive, these will oppose each other and, if they are of similar magnitude, result in a weakly positive or negative total effect.
This is easy to demonstrate with an example based on your causal diagram/DAG with R (hopefully this is sufficiently self-explanatory to make sense to non R users):
set.seed(1)
N <- 100
X <- rnorm(N)
M <- X + rnorm(N)

So $X \rightarrow M$ is positive with magnitude 1.
Now let us simulate $Y$ such that $M \rightarrow Y$ is positive, while the direct effect $X \rightarrow Y$ is negative (with magnitude negative 1):
Y <- M - X + rnorm(N)

then we find the direct effect, by regressing Y on X and M, since conditioning on M will block the path $X \rightarrow M \rightarrow Y$:
summary(lm(Y ~ X + M))

## X           -0.92542

So we have a strong negative direct effect as expected. But when we compute the total effect we obtain:
summary(lm(Y ~ X))

## X            0.02011

which is consistent with your scenario.
Comment: Thank you! I think my main problem now is how to explain this relationship theoretically. I originally hypothesized that X would predict Y (like in a traditional mediation according to Baron & Kenny) but what really confuses me is explaining why there is a direct negative effect. Is this essentially controlling for the other variables? (I actually did Model 21, with moderators significantly moderating the a and b paths, which all panned out, but the mediation part of this is where things are getting confusing which is why my question just addressed the mediation aspect
Comment: Worth noting: the same thing happens with the mediation relationship in Model 4 and Model 21. Insignificant total effect, negative direct effect
Comment: I can't help explain the theoretical relationship. Statistically it all makes sense. I would suggest drawing a causal diagram / DAG with ALL the relevant variables (measured or unmeasured) and see where that takes you.  This may help: https://stats.stackexchange.com/questions/445578/how-do-dags-help-to-reduce-bias-in-causal-inference/445606#445606
Comment: Thank you for your help!
Comment: @psychdoctoralstudent you're welcome. If this answers the question posed in the OP then please consider marking it as the accepted answer and feel free to ask a seperate question about the issue raised in your comments above :)
Comment: Do you know how this type of mediation would be described? I can't find any examples of this occurring. I essentially have the same question as this person who did not receive any answers: https://stats.stackexchange.com/questions/473984/inconsistent-competitive-mediation-vs-suppression-positive-indirect-negative
Comment: I would describe it as opposing indirect and direct effects. It's very common.


Explanation of a step in a proof of Steinhaus' Theorem

Question: Disclaimer: I understand this theorem has been discussed before. I am not looking for a proof however, just a clarification of a mysterious step.
I was reading a proof of the following version of Steinhaus' Theorem, and got stuck on one step:

Theorem (Steinhaus): Let $E \subset \mathbb{R}$ and $m(E)>0$, where $m$ denotes Lebesgue measure on $\mathbb{R}$. Then the set $E-E$
  contains an interval around zero.
Proof: By the Lebesgue differentiation theorem, or, equivalently, by the definition of a Lebesgue point, there exists an interval $I$
  such that
$$m(I\cap E) \geq (1-\epsilon)\,m(I).$$
If the result were not true, there would exist a sequence $x_n \rightarrow 0$ with $x_n \not \in E-E$. Take $n$ large enough that $|x_n|<\epsilon\, m(I)$. Then $x_n +E \subset \mathbb {R} \setminus E$, but
$$\mathbf{m(I\cap (x_n+E))\geq (1-3\epsilon)\,m(I)}$$
(since Lebesgue measure is invariant under translations.) Since $E$ and $\mathbb R \setminus E$ are disjoint, this is a contradiction.

The part I am having difficulty with is in bold characters. I believe it follows from the following:
\begin{align*}
m(I\cap (x_n+E)) & = m(x_n+(I-x_n)\cap E) \\
& = m((I-x_n)\cap E) \\
& \geq m(I) - 2|x_n| - m(I \setminus E) \\
& \geq (1-3\epsilon)\,m(I)
\end{align*}
Is this correct? If not, could you point out the correct steps? Thanks!
Note: For the sake of completeness,
$$E-E:=\{x-y:\ x,y\in E \}.$$
Comment: Is that a typo $E-E$?
Comment: @GregoryGrant it is not. in general the theorem holds for $A+B$ where $A$ and $B$ are both o nonzero measure. $E-E$ is a special case.
Comment: Ah you mean $E-E=\{a-b\mid a,b\in E\}$.  I thought it meant set minus in which case it would be $\emptyset$.
Comment: @GregoryGrant Yes. I added a remark to avoid confusion :)
Answer: HINT:
$$\mu (I \cap (x + E) ) = \mu ( (I- x) \cap E) \ge \mu ( I \cap E) - \mu ( (I \backslash (I - x) ) \cap E)\ge \mu ( I \cap E) - \mu(I \backslash (I - x) ) $$
and $\mu(I \backslash (I - x) )= |x|$ if $I$ fixed and $x$ small enough.
${\bf Added:}$ In fact, this seems to be true: if $\mu(I \cap E) \ge (\frac{1}{2} + \delta) |I| $ then $E - E$ will contain the interval $(-2\delta|I|, 2 \delta|I|)$.
Comment: That is very interesting; never thought about that. What I find most fascinating about this result is its generalization to Haar measures.
Comment: This looks good! But I am not sure where (in the proof I posted), a factor of $2 \epsilon$ came from. According to your calculation, only one factor of $\epsilon$ is introduced from $I \setminus (I-x)$
Comment: @GaussTheBauss:    the factor of $2\epsilon$ is perhaps from $\mu( I \Delta (I-x))$. But $\mu(I \backslash (I-x))$ does the trick already.
Comment: Do you mean by $\delta$ symmetric difference ($\Delta$)? If so, Then I see what you are saying.
Comment: Nevermind! you caught that :) Thanks a lot for your help :)
Comment: @GaussTheBauss: You are welcome! A nice result. If you use the fact that $\mu(E) = \inf_{U = \overset{\circ}{U}\supset A} \mu (U)$ and every open subset is a disjoint union of intervals you can find such an $I$ by hand
Comment: @GaussTheBauss: Oh that's nice, never thought of that. I wonder how would the proof work, since we may not have those nice subsets like the intervals. Ah, maybe some regularity of the measure would work, to squeeze it between a compact and an open. OK, have to think about that.
Comment: Yes. I believe what is crucial is invariance under he group operation. In $(\mathbb {R},+)$, it's Lebesgue measure. In $(\mathbb{R} \setminus \{ 0 \},\cdot)$, the measure is $\frac {dx}{x}$.


Send contact form results to google drive spreadsheet

Question: Is it possible, after form submission (Webform), that the data is immediately sent to spread-sheet in Google drive or some kind of similar application?
Simple fields like :
date, time, first name, last name, webform title.
Answer: There is a module that claims to do so (I haven't used it myself but this would be a good starting point): Webform to Google Docs

This module inserts Webform submissions as new rows in a Google Docs spreadsheet. In the future it may handle updating of entries as well as saving submissions into "docs" as well as "spreadsheets".


Why there are same node in path in my query in neo4j?

Question: There is cypher sql like this:
match p=(:Devices{name:"18.104.22.168"})-[r:Cost*..6]->(:Devices{name:"220.127.116.11"}) with p return p;

Then it's return:
{u'p': (220.127.116.11)-[:Cost {Cost: 21}]->(184.108.40.206)-[:Cost {Cost: 92}]->(220.127.116.11)-[:Cost {Cost: 82}]->(184.108.40.206)-[:Cost {Cost: 91}]->(126.96.36.199)-[:Cost {Cost: 56}]->(126.96.36.199)-[:Cost {Cost: 24}]->(18.104.22.168)}

There is a ring in my path and how to avoid this condition.
Finally why my query is so solw and query
a path under in 10 depth will spend about 1000s-2500s.
There is my config:
dbms.memory.heap.initial_size=4096m
dbms.memory.heap.max_size=9192m
dbms.memory.pagecache.size=10g
dbms.threads.worker_count=16

Answer: Perhaps you meant to specify a path of between 1 and 6 hops, rather than exactly six:
match p=(:Devices{name:"22.214.171.124"})-[r:Cost*1..6]->
  (:Devices{name:"18.104.22.168"}) with p return p;

Comment: Thanks,but there also will spend many time in select path and get result.How to let select be fastly?
Comment: Could you rephrase your question please? I did not understand the meaning. Do you mean you want the query to return faster? Is there an index on `:Device` name property?
Comment: Yes,I want the query to return faster.Now I query a path  will spend about 1000s if the max hops is 10。
Comment: One specific question at a time please. If the first answer solved your initial question, can you accept the answer, an open a new question with regards to increasing performance. Post a link in the comment.
Comment: Ok,thanks  for your suggestions!I meant a path every node only  have one and avoid the ring.Doest't like this:  {u'p': (188.8.131.52)-[:Cost {Cost: 21}]->(188.8.131.52)-[:Cost {Cost: 92}]->(188.8.131.52)->


mysql's binlog only reaches 50mb max before rotating - how to increase?

Question: I run a high traffic MySQL server - and I have observed that my binlogs only get to as big as 50mb, and MySQL creates a new one again.
I already have max_binlog_size set to 1GB - but for some reason - MySQL wont honor it. Are there any other settings that I should be aware about?
I'm on MySQL 4.1.22, CentOS 5 (managed server from LiquidWeb).
root@host2 [~]# mysqladmin variables | grep bin
| binlog_cache_size               | 32768                                       |
| innodb_locks_unsafe_for_binlog  | OFF                                         |
| log_bin                         | ON                                          |
| max_binlog_cache_size           | 18446744073709551615                        |
| max_binlog_size                 | 1073741824                                  |
| sync_binlog                     | 0                                           |

And one more observation: based on "ls -al" output, the date of the binlogs are almost identical in the minutes part, that is, almost always rotated on the 41st minute of every hour.
This is strange because I can't find any cron scripts that could have done this. I asked the LiquidWeb sysadmins and they say they did not control this also.
So, any ideas anyone?
---
root@host2 [~]# ls -al /home/master_mysql/
total 1069004
drwxr-xr-x  3 mysql mysql     4096 Nov 15 23:41 ./
drwx--x--x 13 root  root      4096 Nov 14 17:15 ../
-rw-rw----  1 mysql mysql      122 Nov 14 19:42 mysql-bin.000001
-rw-rw----  1 mysql mysql 27841530 Nov 14 21:41 mysql-bin.000002
-rw-rw----  1 mysql mysql  7899803 Nov 14 21:55 mysql-bin.000003
-rw-rw----  1 mysql mysql       79 Nov 14 21:56 mysql-bin.000004
-rw-rw----  1 mysql mysql 16789873 Nov 14 22:41 mysql-bin.000005
-rw-rw----  1 mysql mysql 33813877 Nov 14 23:41 mysql-bin.000006
-rw-rw----  1 mysql mysql 48819373 Nov 15 00:41 mysql-bin.000007
-rw-rw----  1 mysql mysql 41505054 Nov 15 01:41 mysql-bin.000008
-rw-rw----  1 mysql mysql 44608575 Nov 15 02:41 mysql-bin.000009
-rw-rw----  1 mysql mysql 40341521 Nov 15 03:41 mysql-bin.000010
-rw-rw----  1 mysql mysql 33625553 Nov 15 04:41 mysql-bin.000011
-rw-rw----  1 mysql mysql 28685183 Nov 15 05:41 mysql-bin.000012
-rw-rw----  1 mysql mysql 28054132 Nov 15 06:41 mysql-bin.000013
-rw-rw----  1 mysql mysql 31718242 Nov 15 07:41 mysql-bin.000014
-rw-rw----  1 mysql mysql 34437340 Nov 15 08:41 mysql-bin.000015
-rw-rw----  1 mysql mysql 39474942 Nov 15 09:41 mysql-bin.000016
-rw-rw----  1 mysql mysql 43580287 Nov 15 10:41 mysql-bin.000017
-rw-rw----  1 mysql mysql 51165432 Nov 15 11:41 mysql-bin.000018
-rw-rw----  1 mysql mysql 48298102 Nov 15 12:41 mysql-bin.000019
-rw-rw----  1 mysql mysql 44044967 Nov 15 13:35 mysql-bin.000020
-rw-rw----  1 mysql mysql 53665390 Nov 15 14:41 mysql-bin.000021
-rw-rw----  1 mysql mysql 46259278 Nov 15 15:41 mysql-bin.000022
-rw-rw----  1 mysql mysql 44675487 Nov 15 16:41 mysql-bin.000023
-rw-rw----  1 mysql mysql 41288305 Nov 15 17:41 mysql-bin.000024
-rw-rw----  1 mysql mysql 45883369 Nov 15 18:41 mysql-bin.000025
-rw-rw----  1 mysql mysql 40055136 Nov 15 19:41 mysql-bin.000026
-rw-rw----  1 mysql mysql 39884190 Nov 15 20:41 mysql-bin.000027
-rw-rw----  1 mysql mysql 43919061 Nov 15 21:41 mysql-bin.000028
-rw-rw----  1 mysql mysql 45474412 Nov 15 22:41 mysql-bin.000029
-rw-rw----  1 mysql mysql 43899660 Nov 15 23:41 mysql-bin.000030
-rw-rw----  1 mysql mysql  3625113 Nov 15 23:45 mysql-bin.000031
-rw-rw----  1 mysql mysql     1116 Nov 15 23:41 mysql-bin.index
drwxr-xr-x  2 root  root      4096 Nov 14 19:00 restore_point_20091114/
---

Thanks!
Answer: Given that the sizes are nowhere near identical, it's not the size limit being reached, and the exact timing is a dead giveaway -- MySQL will rotate it's binlog whenever it is restarted, or when you tell it to reopen it's other (system) logs -- typically something that logrotate (or another log rotation tool) will do as part of it's operation.  Look for what's rotating your logs (if LiquidWeb are supposed to be managing that for you, be afraid... be very afraid).
Answer: I Agree with womble, max_binlog_size should do it, but it does look like you are getting logs flushed / rotated for you.  Check /etc/crontab or any crons inside of /var/spool/cron for any thing odd.  Also, maybe set your my.cnf with sql_log_off = on ( im at 5.1 but this should work for you) to get some more info in your mysqld.log, Although alot could just be garbage to look at.  Do you have any frontend software that could possibly be doing this? Good luck.


How to set listener into Flex datagrid using java as back-end

Question: I am using Java as back-end. From server side i created simple service that retrieves data from the database. From Flex side i created simple datagrid and filled it using my java service. Everything works perfectly but i want to set something like listener to datagrid that when new data will be entered to database my flex datagrid automatically will be refreshing. I think that i need somethings from server side that will be waiting from new data and when it appears then should somehow notify flex. It is possible to do that ?
Comment: If you want your server to tell the Flex UI tha something has changed with the data; then you'll need to use a server-side software that supports push notifications; such as LiveCycle or GraniteDS.
Comment: @Reboog711 BlazeDS supports push-messaging thats why there's messaging-config.xml. I've used that.
Comment: I use BlazeDS to transfer data from Java to Flex but i still don't know how to do this dynamically without button like refresh.
Comment: I'm not sure what else to say I haven't said.  You need to use a server-side software that supports push notifications; such as LiveCycle or GraniteDS.  I do not believe that BlazeDS supports that.  ( The functionality was not added to BlazeDS because Adobe wanted to keep some advanced functionality in LiveCycle to entice enterprise customers to get on board )
Comment: Push notifications it is what i need. Thank you for a tip :)
Answer: Just look into this thread on Stack Overflow. BlazeDS offers push-notification which can solve your problem of sending update to client without getting request for the same.
The BlazeDS's sample chat application uses push notifications. You can check for the same at your BlazeDS deployment url [BlazeDS root url]/samples/runtimeconfig-messaging/index.html


How to display external data using custom form in a Drupal page?

Question: I have created a form custom module for get data from an external url.
$requestType = drupal_http_request('http://www.example.in/php/example/getSampleType.php',$options);
$loomType =drupal_json_decode($requestType->data);

This is my Form

Using this result I have created checkboxes and select a value from checkbox then submit the data.
function myForm_form_submit($form, &$form_state) {

$form_state['rebuild'] = TRUE;
$url='http://www.example.in/php/example/exampleSort.php';
//$data1 = http_build_query($form_state['values']['check'], '', '&');

$checked = array();
foreach($form_state['values']['check'] as $key => $val) {
array_push($checked, $val);
  }
$mychecked=checking($checked);

$checkedType = array();
foreach($form_state['values']['checktype'] as $key => $val) {
array_push($checkedType, $val);
  }
$loomType=checking($checkedType);

$datas=array("sampleMachine"=>$mychecked, "sampleType"=> $loomType);
$data =json_encode($datas);
$option = array(
            'method' => 'POST',
            'data' => $data,
            'headers' => array('Content-Type' => 'application/json'),
    );
//$headers = array('Content-Type' => 'application/json');

$response =drupal_http_request($url,$option);

echo "
";
print_r($response);
echo "
";

}
I got some result. Now I want to display those results in my drupal page. How can I do that..I am using Drupal 7.
I want to display this in Drupal page in specific format
Comment: This question is really broad. Typically a form has a build, validation and submit functions as briefly detailed here. https://www.drupal.org/node/1419390 Then you display the results in any 1 of many ways, an example can be found in the Examples module for developers, or similar questions here: http://drupal.stackexchange.com/questions/54374/how-do-i-print-results-after-submitting-a-drupal-form
Comment: But I didnt understand how to display myresult
Answer: Not sure why you want to create a custom module for this, since ... there is a module that can "*display JSON results in a Drupal page" ... i.e. the Views JSON Query module. Some details from its project page:

JSON Query is a Views 3 plugin that adds native JSON query generation. It allows you to parse JSON using Views' graphical query builder.
  It works much like Views XML Backend but with JSON.

And a screenprint from that same page:

For more details, read about it in the article about "Show external JSON data in Drupal Views".
PS: Similar solution if your input format is XML (instead of JSON), using Views XML Backend.
Comment: Using this module I can create check boxes ?
Comment: Correct me if I'm wrong, but the equivalent of your "example form" would become an exposed filter of your view. Or am I missing something?
Comment: I have installed above mentioned modules and tried to create views. In query settings field I have added  the url http://www.example.in/php/example/exampleSort.php It displaying like this  {
  "nodes" : [
    {
      "node" : {
        "value" : ""
      }
    },
    {
      "node" : {
        "value" : ""
      }
    },
    {
      "node" : {
        "value" : ""
      }
    }
  ]
}
Comment: Your last comment really looks like a new question to me, which you shuld post as a new question. Also, looking at your profile I noticed you don't have the "informed" badge. Which is probably also why you're not aware of what's written in http://drupal.stackexchange.com/help/someone-answers .
Comment: Thank you for ur information. I am not able to display my Json result using Views JSON Query .
Comment: Should I create custom view for displaying the result. suggest me the best solution for this.
Comment: yes, that's also what is suggested in the linked article: "***Create a new view and choose Json option at Show select box:***"
Comment: I have tried this. But it doesn't work.
Comment: Please be more specific about what you ***tried***, and explain ***what*** doesn't work (I hope you understand that it is impossible to enhance my answer without such information). Maybe can you edit your answer to include a TEXT-version (not an image) of the JSON (sample) file that you receive from that external URL?
Comment: I have given json file url and rowapath in Views query settings by referring this(Show external JSON data in Drupal Views) article which you share before. But it doesn't give proper result to me. My json array is {"RESULT":"SUCCESS","MACHINES":["Airjet","Waterjet","Rapier"]}
Comment: Try setting the value for "Row Apath" to "/ " (without the quotes). If that doesn't help, try "." (single dot, without the quotes).
Comment: When I setting Row Apath '/' it displays a json structure.  Here what would be the 'key chooser' of field value?
Comment: I'm not sure, but you may now have run into the support issue at https://www.drupal.org/node/2457437 (and I don't know what the answer to that issue is either). I also noticed comment #4 in that issue, is that "you" who posted it there? **Hint**: have a look at https://www.drupal.org/node/2457877#comment-10800662 (comment nr 8), and check if the patch there (in nr 6 attached) does help in your case.
Comment: I have made changes according to  drupal.org/node/2457437 page. Unfortunately it doesn't work for me. anyway thank you for your reply.
Comment: Is there any other way to display json result in a drupal page?
Comment: Do you have some way to have those data from that external url formatted as XML instead of JSON? Other attempt: is it possible for you to get access to the database where those JSON data are related to, if so what is the format of that database, like is it SQLite, Oracle, MS SQL, MySQL, some sort of PDO compliant database?
Comment: sorry.. I want it in JSON format and I don't have permission to  access the database.
Comment: OK, thanks for clarifying, I was just trying to find possible alternatives for you (i.e.: via module "forena", you know that one?). I need some more time to do some more experiments / research (I'm interested in finding a way to make "your" JSON sample work also). No guarantee, but if I can get it to work I'll let you know about it).
Comment: ok.. thank you.  I haven't worked with Forena module.
Comment: You don't know what you're missing then ... have a look at some of my answers (tagged with forena) if you want to get an idea. Disclosure: I'm a co-maintainer of it ...
Comment: But Forena module is used to create reports right..
Comment: Yes, creating reports is one of the reasons to use Forena. It can also create Charts. It can "read" the data from a PDO compliant (external) database. And it can also "make" the retrieved data available in either JSON format or XML format (instead of a rpt), and you can export the data in a report to CSV, XLS, PDF, DOC, etc. And your "example form" could be implemented as a "report parameter form".


Display of View (using grid) is unevenly distributed

Question: Note: as a neophyte user, I'm not allowed multiple links or images. It has been suggested that I edit the hyperlinks so they're not quite right. Hopefully you can sort out what's going on.
Here is my view with taxonomy terms in columns, but you see that the columns are a bit wonky and not evenly distributed.
These are the the grid settings

And this is the page h ttp://imgur.com/puH2v1M
Thanks.
Comment: Your View looks fine. It would be better to see the underlying html and the styles applied to it.
Answer: My guess (I cannot be sure without seeing the HTML and CSS) is that the grid display uses HTML tables to create the grid. Because this looks exactly like what HTML tables do: they adjust their column width to the content in it. For instance, "General Fiction" is longer than "Genre" so the first table column is wider than the second. Because your view is grouped, every group would render a separate table, so that's why the columns cannot align.
Assuming that tables are indeed the cause, the solution would be to add custom CSS setting the width of  elements in this view to 33.3%. (How you can do that, depends on your theme setup and is beyond the scope of this answer.)


Double integral - domain of integration

Question: Calculate the following double integral: $ \int \int_S x\; dx \; dy $, where $S$ is the region limited by the circle of radius 1 and center (0,1) and the line that pass through the points (2,0) and (0,2)
I think that this integral must be
$$ \int_0^1 dx \int_{-x+2}^{\sqrt{1-x^2}+1} x \; dy $$
but the answer is $\frac{1}{3}$ and this integral is $\frac{1}{6}$. What am i doing wrong?
Thanks in advance!
Comment: everything seems to be fine.
Answer:
(after having spent some time working in the wrong region):
The statement of the boundaries is ambiguous, because they apply equally well to the blue or the green region shown in the graph above.  But it wasn't a complete waste of time to integrate in the wrong place, as I will describe below.
The equation of the circle is $ \ x^2 \ + (y-1)^2 \ = \ 1 \ $ , so the functions for the "upper and lower" semicircles are $ \ y \ = \ 1 \ \pm \ \sqrt{1-x^2} \ . $  The blue region is bounded above by the upper semi-circle and below by the line $ \ x + y = 2 \ $ .  The intersection points of the line and circle are $ \ (0,2) \ \text{and} \ (1,1) \ . $  So the double integral is
$$ \int_0^1 \int^{1 + \sqrt{1-x^2}}_{2-x} \ x \ \ dy \ dx \ = \ \int_0^1  \ xy \ \vert^{1 + \sqrt{1-x^2}}_{2-x} \ \  dx  $$
$$ = \ \int_0^1  \ x \ \left[ \ (1 + \sqrt{1-x^2}) \ - \ (2-x) \ \right] \ \  dx \ = \ \int_0^1  \ x^2 \ - \ x \ + \ x \sqrt{1-x^2} \ \  dx   $$
$$ =   \ \left[ \ \frac{1}{3}x^3 \ - \ \frac{1}{2}x^2 \ - \ \frac{1}{3} (1-x^2)^{3/2} \ \right] \ \vert_0^1    $$
$$ =   \ \left( \ \frac{1}{3} \ - \ \frac{1}{2} \ - \ 0 \ \right) \ - \left( \ 0 \ - \ 0 \ - \ \frac{1}{3}  \ \right) \ =  \ \frac{1}{6} \ , $$
which apparently does not agree with the "given answer".  So who's right?
Let's take the integration over the green region, which is bounded below entirely by the lower semi-circle, bounded above by the upper semi-circle over $ \ [-1 , 0 ] \ $ , and above by the line over $ \ [0 , 1] \ . $  So we have two integrals here:
$$ \int_{-1}^0 \int^{1 + \sqrt{1-x^2}}_{1 - \sqrt{1-x^2}} \ x \ \ dy \ dx \ \ +   \ \ \int_0^1  \int^{2-x}_{1 - \sqrt{1-x^2}} \ \ x \ \ dy \ dx   $$
$$ = \ \ \int_{-1}^0 \ \ x \  \left[ \ (1 + \sqrt{1-x^2}) \ - \ ({1 - \sqrt{1-x^2}}) \ \right] \ \ dx $$
$$  +   \ \ \int_0^1   \ x \ \left[ \ (2-x) \ - \ (1 - \sqrt{1-x^2})  \ \right] \ dx   $$
$$ = \ \ 2 \ \int_{-1}^0 \ \ x \   \sqrt{1-x^2} \ \ dx \ + \ \ \int_0^1  \ x \ - \ x^2 \ + \ x \sqrt{1-x^2} \ \  dx $$
$$ =   \ \left[ \  - \ \frac{2}{3} (1-x^2)^{3/2} \ \right] \ \vert_{-1}^0  \ + \   \ \left[ \ \frac{1}{2}x^2 \ - \ \frac{1}{3}x^3 \ - \ \frac{1}{3} (1-x^2)^{3/2} \ \right] \ \vert_0^1      $$
$$ =   \ \left[ \ -\frac{2}{3} \ + \ 0 \ \right] \ + \ \left[ \ \left( \ \frac{1}{2} \ - \ \frac{1}{3} \ - \ 0 \ \right) \ - \left( \ 0 \ - \ 0 \ - \ \frac{1}{3}  \ \right) \ \right] $$
$$  = \  -\frac{2}{3} \ + \ \frac{1}{6} \ + \ \frac{1}{3} \ = \ -\frac{1}{6} \ . $$
What was the point of doing this?  Together, the green and blue regions cover the entire circle, which is symmetrical about the $ \ y- $ axis.  We are integrating $ \ x \ $ , a function with odd symmetry (about the $ \ y-$ axis) over this region.  So the integral of this function over the circle is zero.  And indeed, the integrals over the blue and green regions have opposite signs.
So I believe the result of $ \ \frac{1}{6} \ $ for the blue region is reliable.  My suspicion is that the solver may have made an error summing the fractions (I've seen it happen...).

Double integral - domain of integration


How can I automate this task ? (automatic contouring for radiotherapy)

Question: I've just started my residency as a radiation oncologist. I have a little background in programming (Python, VBA).
I'd like your insights on an issue I have at work.
The issue : For each patient, the radiation oncologist needs to do a contouring. Basically, he contours the main structures (like the aorta, the heart, the lungs, and so on) on a CT scan. This is essential for computing the spatial distribution of the radiations (because you want to avoid those structures). The contouring is done within a 3rd party software (called Isogray). The CT scans come from the hospital database and the radiation distribution is computed on another software.
It takes at least one hour to do a complete contouring. Multiply that by each patients (maybe a dozen per week) and by each oncologists (we are a team of 15 members) and you can see that it represents hundred (maybe even thousand) manhours every year.
There exists softwares that do this automatically, but the hospital doesn't want to rent/buy them. But, seriously, how hard can this be to do a little automation ? Can't I do this myself ?
My plan of action : Here I'd like your insights. How can I automate this task ? The first thing is that I can't change anything within Isogray, so I need to do the automation externally. What I think I should do :

Create a database of the historical contourings : this means I need to be able to read what Isogray uses as an output files
Design an automatic model : I'm thinking deep learning models here. I don't know if there's anything more optimal to do than calibrating a deep learning model on the contoured CT scans I already have
Create a little software : based on the automatic model, the software will take a 'not contoured' Isogray file and turn it into a 'contoured' file. The oncologist only needs to load the new file into Isogray and validate the contouring

What do you think ? Do you see an easier way to do that ? I don't know anything about Isogray (I just know how to use it). Do you think this is doable? What information do I need before I start this project ?
Any insights will be welcomed :)
Answer: From what I have understood it is a problem of semantic segmentation.
You have an input image of N dimensions (or black and white) and you use the neural network to indicate which regions correspond to a specific organ.
You can use an architecture like the U-Net for this task: https://medium.com/@keremturgutlu/semantic-segmentation-u-net-part-1-d8d6f6005066
What I do not know is if the degree of reliability would be very high, that depends on many factors.
Neural networks look for differentiating patterns to discriminate zones, the first important component is shape and color. That is why it is more difficult when both the color and the shape are very different.
On the other hand you will need a lot of images but you can create a process called data-augmentation to generate more (artificial).
Another method that is currently used is to work in reverse, we know that the problem of image segmentation is difficult. But you can design a program that simulates real images where segmentation is known perfectly.
There are only some keypoints, I hope I have helped you.
EDIT:
Semantic segmentation in biomedic context: https://towardsdatascience.com/review-u-net-biomedical-image-segmentation-d02bf06ca760
Answer: You need to provide more background on the specifics on the contouring, especially given the fact that this is for medical diagnosis. Truthfully, I wouldn't try and automate this for liability reasons.
If you make an error someone it could cause a misdiagnosis, which as you already know can lead to numerous problems including lawsuits and death. The nice thing about 3rd party products is that it is already being tested robustly against numerous scenarios and approved for medical usage and liability reasons.
I'm pretty sure you could make a masters thesis doing something like this
With that being said, there is a nice github repo for problems like this that I think you could potentially start generating ideas from.


How to transfer all the handlers from one deferred to another?

Question: Let's say I have a $.Deferred and a jqXHR object. Is there a way to transfer all the handlers bound to the deferred (then, always, done, fail) over to the XHR object (which, as I understand it, is an extension of Deferred)?

Here's what I had in mind:
$.ajaxOne = function(options) {
    var xhr = null;
    return function() {
        if(xhr) xhr.abort();
        xhr = $.ajax(options).always(function() {
            xhr = null;
        });
    }
}

I wanted to create a function, similar to $.ajax, except that if you call it multiple times in rapid succession, it will abort the last request and only complete the most recent one. This is useful in many scenarios where you want to validate a user's input.
For example, you might want to check if a username is taken, but if they start typing in the username field again after you've started your ajax call, you don't care about the last result, only the most recent one.
Also, I don't think requests are guaranteed to return in the same order they went out (I suppose depending on your server setup), so you could have a syncing issue as well.
Anyway, the problem with the above code is that because it returns a function, you can execute your ajax call whenever you like, but you can't bind your completion handlers to it. So I have to somehow mix the deferred handlers in and rebind them to the XHR object.
Comment: I don't think that can be done... why don't you resolve the deferred using jqXHR callbacks.... `xhr.done(function(){
    deferred.resolveWith.apply(deferred, arguments);
}).fail(function(){
    deferred.rejectWith.apply(deferred, arguments);
})`
Comment: @RocketHazmat: In this particular scenario, I essentially want to build a 'ajax' object without immediately executing it. So I was thinking about returning a Deferred instead so that users could still bind their events to it, and then when they execute it, it would run the ajax call... I'll post a more concrete example if you want, I admit having not fully thought it through :-)
Comment: @RocketHazmat: I'm actually using it in combination with debouncing. I debounce for ~300ms, but if the AJAX takes a really long time to return, it can still fire off twice. I *could* delay executing the new AJAX call until the last one returns, but that would provide an inferior user experience...the calls could stack up and they would be waiting a long time for the latest results.
Comment: @RocketHazmat: I don't know how your `$.Deferred` example would work...you haven't bound anything to `$.ajax` -- only that object knows when the call has come back. I think Arun has the best solution so far.
Comment: Out of curiosity, why do you have this setup?  Why didn't you just use the jqXHR object, instead of making a new `$.Deferred`?  Also, in your solution do you want your deferred to be resolved or not in the end?
Comment: @Mark: Would you then want the user to be able to bind to the callback of the AJAX call or not?  Would something like this work? `$d = new $.Deferred; /* your code... make sure to call d.resolve() somewhere */ return d.then(function(){ $.ajax({}); }).promise();`?  I'm pretty sure you can do that.
Comment: `"except that if you call it multiple times in rapid succession, it will abort the last request and only complete the most recent one"`  This is called "debouncing".  Check out this plugin: http://benalman.com/projects/jquery-throttle-debounce-plugin/
Comment: @Mark: That example was before I knew what you were trying to do.  It doesn't really make much sense now ;)
Answer:
Let's say I have a $.Deferred and a jqXHR object. Is there a way to transfer all the handlers bound to the deferred (then, always, done, fail) over to the XHR object (which, as I understand it, is an extension of Deferred)?

More or less, yes, but not in the way you expected. Instead of "moving handlers", you just resolve the deferred (that has the handlers) with the XHR deferred. This will make the deferred adopt the state of the ajax promise - or not, since jQuery is not Promise A+-compatible. So you will need to put the triggers as handlers manually:
var deferred = $.Deferred(),
    xhr = $.ajax(…);
xhr.done(deferred.resolve).fail(deferred.reject).progress(deferred.notify);

However, a use like that is discouraged, just use xhr wherever you needed deferred - they're equal. Or use xhr.then() to create a brand new promise object that resolves exactly like xhr will.

Anyway, the problem with the above code is that because it returns a function, you can execute your ajax call whenever you like, but you can't bind your completion handlers to it. So I have to somehow mix the deferred handlers in and rebind them to the XHR object.

You still can return each xhr object from that returned function, and bind your handlers to that. In case it is aborted, its error handlers will be called.
$.ajaxOne = function(options) {
    var xhr = null;
    return function(name) {
        options.data = name;
        if (xhr) xhr.abort();
        return xhr = $.ajax(options).always(function() {
//      ^^^^^^
            xhr = null;
        });
    }
}
var checkUserAccount = $.ajaxOne({…});
$input.keyup(function(e) {
    checkUser(this.value).done(function(ajaxResult) {
        // do anything here with the ajaxResult from the latest call
        // if there was another keyup event, this callback never fires
    });
});

Also, I don't think requests are guaranteed to return in the same order they went out (I suppose depending on your server setup), so you could have a syncing issue as well.

Not if you call abort on each old one when the function is called again - that will hold the invariant that there is only at most one active ajax request at a time.

I wanted to create a function, similar to $.ajax, except that if you call it multiple times in rapid succession, it will abort the last request and only complete the most recent one.

Sounds pretty much like an event stream. You will want to have a look at Functional Reactive Programming!
Comment: Returning `xhr` doesn't solve the problem. Promises can only be resolved once. The idea behind `ajaxOne` is that you create an instance of it, bind your completion handlers, and then execute it as many times as you like. [RxJS](https://github.com/Reactive-Extensions/RxJS) might be a better fit; not sure. Haven't tried it out yet.
Comment: Hm, returning multiple promises (one from each function call) would work - see my extended example code. Of course, [a row of promise is just a stream](http://stackoverflow.com/a/17414193/1048572) :-) Yes, if you want to attach a single handler that is fired multiple times then FRP is the solution (I've mentioned it in the last paragraph); you might want to have a look at Bacon.js as well.
Answer: Came up with this:
function AjaxOne(options) {
    this.options = options;
    this._xhr = null;
    this._always = [];
    this._success = [];
    this._fail = [];
};

$.extend(AjaxOne.prototype, {
    always: function(cb) {
        this._always.push(cb);
        return this;
    },
    done: function(cb) {
        this._success.push(cb);
        return this;
    },
    fail: function(cb) {
        this._fail.push(cb);
        return this;
    },
    then: function(success, fail) {
        this._success.push(success);
        this._fail.push(fail);
        return this;
    },
    run: function(options) {
        if(this._xhr) {
            this._xhr.abort();
        }
        this._xhr = $.ajax($.extend({},options,this.options,{context:this}))
            .always(function() {
                this._xhr = null;
                for(var i=0; i<this._always.length;++i) this._always[i].apply(this,arguments);
            })
            .done(function() {
                for(var i=0; i<this._success.length;++i) this._success[i].apply(this,arguments);
            })
            .fail(function() {
                for(var i=0; i<this._fail.length;++i) this._fail[i].apply(this,arguments);
            });
    }
});

Seems to be working pretty well so far.... but it doesn't answer my original question.
So a comprehensive answer would be: you can't copy the callbacks from one deferred to another. I tried making copies of the deferred in various ways, $.extend({}, myDeferred) I couldn't get anything to work. I think you have to manually make copies of each method and fire off the appropriate callbacks, similar to what I've done.
You can propogate the callbacks off to the original deferred as Arun suggests in his comment (although I think his syntax is slightly off; according to the docs you don't need the .apply in there; the purpose of the 'with' methods is to allow you to set a context). In my case I wanted to be able to fire the methods more than once, so that doesn't work for my scenario.
Comment: All objects that can be cast to jQuery promises (including deferreds, promises, or even [jquery collections](http://api.jquery.com/promise/)) do have a `promise` method. `then` is broken because it is expected to return a new promise for the return values of the handlers, not the original promise (admittedly, jQuery's `then` was broken until v1.8 as well, see http://stackoverflow.com/q/9583783/1048572, http://stackoverflow.com/q/12011925/1048572, http://stackoverflow.com/q/5436327/1048572)
Comment: No, please don't do this. Your [`then`](http://api.jquery.com/deferred.then/) method is broken, and to have your `AjaxOne` instances be identified as promises they should have a [`.promise()` method](http://api.jquery.com/deferred.promise/)
Comment: @Bergi Promises don't have a `.promise` method, deferreds do. How's my `then` broken?
Answer: Fiddle here.
I have implemented without using deferred objects.
The keyup Event -
$("#uID").keyup(function () {
    console.log("KeyUp")
    var textElement = this;
    clearTimeout(textElement.timer);
    if(textElement.xhrReq && textElement.xhrReq.abort){
        textElement.xhrReq.abort();
    }
    textElement.timer = setTimeout(function(){
        console.log("Invoking validation : " + textElement.value);
        validateUID(textElement);
    }, 1000);
});

In validateUID(), I have assigned the entire XHR object to the input element's property -
textElement.xhrReq = $.ajax({
...
});

One drawback - and I admit it's there - we need to keep the entire XHR object in the element.
Comment: I don't know whether or not this answers the question but it could be written to run more efficiently in particular by keeping various data and the setTimeout callback function in a closure. **[updated fiddle](http://jsfiddle.net/kq0t87k4/6/)**


Why is multicollinearity different than correlation?

Question: I know that someone will probably say that this question is repeated and I will get a negative vote, but I'm very convinced that it's not, or at least it wasn't properly answered. See, we have lots of questions like this, sure. For instance, this one, also this one, this, and also this post, oh and also this post.
By reading all the answers, what I've found is that most people believe that correlation and multicollinearity are the same, or very related, but some very prestigious people (like Peter Flom) says that they are not actually directly related. Also, most answers are not very profound. At least not for someone not so intelligent like me. And there is nothing in the books I have as well (like Angrist and Wooldridge).
So I will take my chances here and ask again: what is the difference between multicollinearity and correlation? How do I check mathematically multicollinearity? What kind of math is behind this?
I'm trying to 'see' the difference mathematically. Can someone help me?
Comment: Correlation is about two variables whereas multicolinearity can be about linear function of arbitrarily many variables. Apart from that I look forward to read some answer. +1
Comment: I believe you misrepresent Peter Flom's answer.  Although the relationship between correlation and multicollinearity may be somewhat subtle, it is direct.  Your questions *are* answered in the links.  For instance, one of them states you can look at the VIF to check for multicollinearity.  The math is called "linear algebra."  Because there is no essential difference--apart from what was just pointed out in Bernhard's comment--there's nothing to see mathematically.
Answer: According to the Wikipedia encyclopedia

In statistics, multicollinearity (also collinearity) is a phenomenon in which one predictor variable in a multiple regression model can be linearly predicted from the others with a substantial degree of accuracy.

So multicollinearity is a special case of correlation. It is more specific in two ways

It relates specifically to the predictor variables in a regression model.
It relates to correlation with a linear combination of multiple variables combined.

Correlation doesn't need to be that linear combination of multiple variables (correlation is about two variables). And correlation describes a much wider phenomena than just this case with predictor variables.
There is a distinction between perfect multicollinearity (a perfect linear relation between variables/predictors) or just multicollinearity (not an exact linear relationship but strong correlation of at least one of the predictors with a linear combination of the other predictors).

Is checking for multicollinearity the same as checking for correlation?
No, not exactly.

what is the difference between multicollinearity and correlation? How do I check mathematically multicollinearity? What kind of math is behind this?

Multicollinearity may occur even when there is little correlation present between individual pairs of predictors. The issue of multicollinearity can occur when there is correlation with one predictor and a linear sum of the other predictors.
Imagine for instance when there are six predictors and a seventh is added as the sum $X_7 = X_1 + X_2 + X_ 3 + X_4 + X_5 + X_6$. The correlation between $X_7$ and the other predictors will only be relatively small. But there will be perfect multicollinearity.
In that example of perfect linear relationship, you can check perfect multicollinearity by computing the rank of the design matrix, and this should equal the number of columns in order for perfect multicollinearity to be absent.
But when $X_7$ has just a tiny bit of difference with the sum $X_1 + X_2 + X_3 + X_4 + X_5 + X_6$ then there won't be perfect multicollinearity. Yet, the predictor $X_7$ is still a lot dependent on the other six (and causing troubles).
In this case you can not easily verify just by the correlations, because these are not very large.  One common method, in this case, is to compute the variance inflation factor (VIF). This VIF expresses how much of the variation/variance/error in the estimate of a coefficient (computed as $s^2 (X^TX)^{-1}$, where $X$ is the design matrix) is due to the interactions with the other variables.
Computational example
Below we created the seven variables as explained above. The seventh is the mean of the previous six with a bit of noise added.
The correlation table (of the design matrix $X$) looks like:
<code> 1.00 -0.30 -0.25 -0.32  0.11 -0.24 0.01
-0.30  1.00  0.29  0.29 -0.12  0.10 0.64
-0.25  0.29  1.00  0.11 -0.54  0.34 0.41
-0.32  0.29  0.11  1.00  0.03 -0.17 0.46
 0.11 -0.12 -0.54  0.03  1.00 -0.44 0.10
-0.24  0.10  0.34 -0.17 -0.44  1.00 0.28
 0.01  0.64  0.41  0.46  0.10  0.28 1.00
</code>
Not very remarkable.
But the inverse of the covariance table $(X^TX)^{-1}$. Has the last entry on the diagonal a large value 6.42. This relates to the error (variance) of the 7th coefficient which is almost 36 times larger/inflated.
<code> 0.15  0.17  0.15  0.15  0.17  0.13 -0.93
 0.17  0.24  0.18  0.18  0.23  0.16 -1.15
 0.15  0.18  0.22  0.16  0.22  0.14 -1.07
 0.15  0.18  0.16  0.21  0.20  0.15 -1.06
 0.17  0.23  0.22  0.20  0.29  0.19 -1.29
 0.13  0.16  0.14  0.15  0.19  0.16 -0.93
-0.93 -1.15 -1.07 -1.06 -1.29 -0.93  6.42
</code>
Below is the table of the design matrix

x_1
x_2
x_3
x_4
x_5
x_6
6 x_7

4
7
6
7
4
5
5.67

4
3
5
4
5
4
4.17

5
5
6
4
4
4
4.67

6
3
5
4
4
8
4.83

3
4
5
5
6
5
4.83

6
4
6
4
3
3
4.33

7
1
2
4
5
3
3.67

5
4
4
6
3
4
4.17

5
6
5
2
3
7
4.50

2
4
5
6
3
5
4.17

3
4
4
4
3
7
4.17

3
5
6
6
2
5
4.33

5
4
4
4
5
4
4.17

4
3
3
4
6
4
4.00

6
6
2
4
6
3
4.67

4
5
3
6
6
1
4.17

5
6
4
6
4
5
5.00

8
3
5
4
4
3
4.50

4
5
5
6
6
4
5.17

6
4
4
7
5
5
5.17

The example is created with this R-code
<code>set.seed(1)

# generate 6 random variables
X_1_6  = matrix(rbinom(120,9,0.5), ncol = 6)

# generate a 7-th variable with a bit noise
x7 = (rowSums(X_1_6) + rbinom(20, 2, 0.5) - 1)/6

# make the design matrix from all 7 variables
X = cbind(X_1_6,x7)

### the correlations
round(cor(X), 2)

### the inverse of the covariance table
round(solve(t(X) %*% X),2)
</code>
Geometric view

I'm trying to 'see' the difference mathematically.

From a geometric point of view you can see regression as projection of the $n$ observations $y$ onto the surface spanned by the $m$ predictor vectors.
These observations can be seen as a point in $n$-dimensional space. The $m$ predictor vectors form a sub-space (m-dimensional, in 2 dimensions you can see it as a surface) within this $n$-dimensional space. The fitted solution of the regression is the point within this sub-space that is closest to the observation.
The image below from this question might help to see this.

We could look perpendicular to the surface spanned by the vectors $x_1$ and $x_2$ above. The coefficients $\beta_1$ and $\beta_2$ of the solution can be seen as coordinates on this surface telling how much of vector $x_1$ and $x_2$ you need to add to get to the solution/prediction $\hat{y}$. (see the question Intuition behind $(X^TX)^{-1}$ in closed form of w in Linear Regression for an explanation of the difference between the $\alpha$ and $\beta$ coordinates in this image)

The axes of this coordinate space are however not perpendicular to each other. The following image illustrates that this creates large changes in coordinates for small changes of a point in space.

The image contains a sample of 100 randomly distributed observations/experiments as the projections/solutions of the fitting/regression. The distribution of this is a circular cloud in the case of Gaussian distributed errors.
The axes $x_1$ and $x_2$ are not perpendicular to each other but are diagonal instead. You can see that this sort of places the lines of the coordinates closer to each other (and these coordinates correspond to the coefficients that are the output of the regression). This means that the variation in this coordinate/coefficient will be larger.
The case of this graphical example is in two dimensions, but you could imagine it as extended to multiple dimensions. Multicollinearity means that at least one of the axes (corresponding to the predictor vector) has a small angle with the combination of the other axes (with the space spanned by those other axes). That means it is not necessarily one single axis and another single axis having a small angle relative to each other (in the 2D case it is), but one axis having a small angle with the subspace created by the other $m-1$ other axes.
In 3 dimensions you can view it as below. Say the axis $x_3$ is sheared and at an angle with the others. You can have this $x_3$ at a very small angle with the bottom plane of the cube (or even inside of it) without the independent angles with $x_1$ and $x_2$ being very small.

See for a related question (with many more links to other related questions) why does the same variable have a different slope when incorporated into a linear model with multiple x variables with
Comment: @whuber I have rephrased it a bit. The point that I tried to convey is that the correlation between individual pairs of predictors is not what makes the multicollinearity, but it is the correlation between linear combinations of predictors.
Comment: "Galton defined what co-relation as a phenomenon that occurs when "the variation of the one [variable] is accompanied on the average by more or less variation of the other, and in the same direction."" [See wiki](https://en.wikipedia.org/wiki/Francis_Galton).
Comment: I get it, but unless you constrain the possible linear combinations, the latter is meaningless.
Comment: @whuber I've been re-reading this post. I am not sure whether I improved it afterwards your comment or whether it is from before, but, after the bit that seems contradicting "Multicollinearity means that at least one of the axes ... has a small angle with the other axes." I directly explain with a followup sentence *"That means it is not necessarily one single axis being close to another single axis (in the 2D case it is), but one axis being close to the subspace created by the other $m-1$ other axes."* and I add a sheared cube image as intuition. Was that not sufficiently clarification?
Comment: It's definitely clearer: great images, too.  But I think it's not generally correct, because multicollinearity is a property only of the spaces generated by the vectors, not of the vectors themselves, whence there is no inherent meaning to "close to the subspace." I suppose you could fix that by insisting all vectors are first rescaled to a common length.  But that's not evidently the case in your diagrams.
Comment: This post is confusing. Even in "linear relationships" pairs of variables often are non-linearly related; and to state that "correlation doesn't need to be a linear relationship" is puzzling, because correlation isn't a relationship at all. The rest is even more confusing because it contradicts itself. "Multicollinearity may occur even when there is little correlation present" means, geometrically, the angles between the axes are all *large,* but later you assert "Multicollinearity means that at least one of the axes ... has a small angle with the other axes." How can both be correct?


Adding an image base field to custom content entity

Question: consider the following situation: I have created a custom content entity with several base fields (string and string_long fields) and it works flawlessly. In addition I want the entity to hold an image field which I defined the same way I did with the other fields:
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    …

    $form_options = array(
        'type' => 'string',
        'weight' => $key,
    );

    $view_options = array(
        'label' => 'hidden',
        'type' => 'string',
        'weight' => $key,
    );

    …

    $type = 'image';
    $settings = array();
    $form_options['type'] = 'image_image';
    $view_options['type'] = 'image_image';

    …

    $fields[$fieldname] = BaseFieldDefinition::create($type)
        ->setLabel(t($sections['labels'][$key]))
        ->setDescription(t($sections['descriptions'][$key]))
        ->setSettings($settings)
        ->setDisplayOptions('view', $view_options)
        ->setDisplayOptions('form', $form_options);
}

Now, why would I get the errors Notice: Undefined index: target_type in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::propertyDefinitions() (line 70 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php). and Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityManager->getDefinition() (line 256 of core/lib/Drupal/Core/Entity/EntityManager.php).?
Anyone has a hint?
Thank you in advance!
Answer: Looks like you need to specify the target_type.
It should get the default from FileItem::defaultStorageSettings(), I am not sure why that doesn't work.
Unrelated, but note that you should not call t() like that, as it makes it impossible for potx to extract translatable strings from your code. Also, watch out for https://www.drupal.org/node/2363099, you need to update it to use nt() then.
Edit: Turns out, the problem is that the code was using setSettings(), which is considered problematic because it replaces all existing settings, including defaults. Switching to setSetting() for specific settings should solve it.
Comment: Ah, you are using setSettings(). Don't. That replaces all existing (default) settings. Use setSetting($key, value) for your own settings, always.
Comment: Well, using `->setSettings('target_type' => 'file')` now gets me to the entity edit form where I get a lot more errors resulting from defaultFieldSettings not being applied. I see errors like `Notice: Undefined index: file_directory in Drupal\file\Plugin\Field\FieldType\FileItem->getUploadLocation() (line 269 of core/modules/file/src/Plugin/Field/FieldType/FileItem.php).` or `Notice: Undefined index: max_resolution in Drupal\image\Plugin\Field\FieldWidget\ImageWidget->formElement() (line 120 of core/modules/image/src/Plugin/Field/FieldWidget/ImageWidget.php).`… Maybe it is a bug?
Comment: Hey, thanks, I did not know that! Now everything works fine! Care to update you answer? I will gladly accept it then.
Comment: Updated the answer.
Answer: You are using wrong formatter type, these is no "image_image" formatter so
$view_options['type'] = 'image_image';

should be
$view_options['type'] = 'image';

for more on how to get proper formatters ids look here
https://www.drupaldump.com/custom-entities-and-how-get-setdisplayoptions-types
Comment: This is a very old issue which was already resolved. By then "image_image" worked…


Load and animate huge images

Question: I have some huge image size which is animated, scrolling to the left. The performance is very bad. I would like to have only 2 images at the beginning. Then user clicks on the left or right arrow i need to show a loader image then pull the images. Is that possible? how? please tell if there are any other way to do.
Answer: I think that this is not the answer that you where looking for but I think that you should only use a simple animation (fade or something else), why?, because the performance of the animation depends to much on the browser the pc (or device) running the browser, the version of the browser, I used to waste a lot of time trying to fix all performance problems on all the browsers.

Load and animate huge images


Python unsupported operand type pyppeteer

Question: Estou tentando utilizar o pyppeteer (um port de puppeteer para python, com basicamente a mesma sintaxe).
Quando tento await page.mouse.click('.jfk-button-narrow', { 'button': 'left' }), levanta-se o erro
 File "C:\Users\Windows 7\Desktop\Scripts\ScriptsPython\PrimevalBrowserManipulator.py", line 9, in main
    await page.mouse.click('.jfk-button-narrow', { 'button': 'left' })
  File "C:\Users\Windows 7\AppData\Local\Programs\Python\Python36\lib\site-packages\pyppeteer\input.py", line 302, in click
    await self.move(x, y)
  File "C:\Users\Windows 7\AppData\Local\Programs\Python\Python36\lib\site-packages\pyppeteer\input.py", line 277, in move
    x = round(fromX + (self._x - fromX) * (i / steps))
TypeError: unsupported operand type(s) for -: 'str' and 'float'

na tentativo de selecionar o botão 'permutar linguas' no Google Translator. Entretanto o script funciona perfeitamente se eu usar algo como await page.mouse.click(1066.0625, 135, { 'button': 'left' }) em que eu escolho o exato pixel a ser clicado (o que não é nem um pouco prático). Então o que há de errado com o .jfk-button-narrow? É exatamente a classe de elemento do botão 'permutar línguas'.
Meu código:
import asyncio
from pyppeteer import launch
async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport({ 'width': 1280, 'height': 560 })
    await page.goto('https://translate.google.com.br/?hl=pt-BR')
    await page.mouse.click('.jfk-button-img', { 'button': 'left' })
    await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
    await browser.close()
asyncio.get_event_loop().run_until_complete(main())

Eu chequei o source e aparentemente o port para python não aceita id/class/name de elemento porém apenas coordenadas de pixel na função page.mouse.click, todavia não estou certo.
Comment: Está dizendo que não é possível executar a subtração `self._x - fromX` quando `self._x` é uma _string_ e `fromX` é um _float_.
Answer: A fim de clicar em um element a partir de seu seletor CSS, é necessário utilizar a classe ElementHandle do pyppeteer implícita no page.click(selector) ao invés de page.mouse.click(coordinates). O código corrigido ficará:
import asyncio
from pyppeteer import launch
async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.setViewport({ 'width': 1280, 'height': 560 })
    await page.goto('https://translate.google.com.br/?hl=pt-BR')
    await page.click('.jfk-button-img', button='left')
    await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
    await browser.close()
asyncio.get_event_loop().run_until_complete(main())


How to solve this exception??Caused by: org.hibernate.TransactionException: Transaction not successfully started

Question: i am new to hibernate and trying to persist a simple object in database.The data is getting saved in the table but then the following exception is thrown.
Caused by: org.hibernate.TransactionException: Transaction not successfully started
Here is my code,please help!
    @Transactional
public void addEmployee(Employee empObj) {
    System.out.println(">>>>>>>>>>>in DAO");

    Transaction tx = null;
    Session session=sessionFactory.getCurrentSession();

    try{
    tx=session.beginTransaction();
    session.save(empObj);
    tx.commit();
    }

    catch (HibernateException e) {
         if (tx!=null)
             tx.rollback();
         e.printStackTrace();
      }

}

Answer: All you have to do is change your method code as follows:
@Transactional
public void addEmployee(Employee empObj) {
    Session session=sessionFactory.getCurrentSession();
    session.save(empObj);
}

If you have indeed configured Hibernate with Spring - as I guess you have, judging from the exception - then a Hibernate Platform Transaction Manager intercepts the method call (implied by @Transactional) and automatically starts a transaction for you. Since a transaction has already been opened per that session, a new one can't be opened.
Comment: Yes its working ,thanks!! now would you please explain to me when to use @Transactional?? what was wrong with my code??
Comment: so does @Transactional handles auto commit and rollback??doesn't one need to close the session after the transaction is over?
Comment: When you use `@Transactional`, as explained Spring opens one for you before the method call, and commits when the method end (or rolls back usually if exception occurs). Think of it as if Spring calls `session.beginTransaction()` before the method call, and `tx.commit();` afterwards
Comment: You never need to close a session as it's usually pinned to a Thread. Just transaction begin and commit | rollback which Spring does for you
Comment: another thing Orid,i found some codes where @Transactional is used at the service layer or in the class which calls the dao methods.could you please explain the the reason behind this or which is more appropriate?
Comment: It's more appropriate at the service layer, since you can span a transaction that uses more than a single DAO
Answer: This is because you are mixing hibernate and spring transactions.
@Transaction is a Part of spring AOP and dose auto transaction handling. you have to have use only a transaction type in your code you can remove either one.


What can I think of the function $F$ that's being used for most(?) explicit first order ODEs?

Question: Almost anything on this topic only deals with how to solve ODEs, but so far I couldn't find one single site defining this ominous $F$ that's being used so often, like in Wikipedia or in my script (not English, so I'll rather quote it instead of linking):
First of all F is introduced without definition as $F(y)=y'$ for a given vector y; it is then used like $F(t_0, y(t_0))=y'(t_0)$ which looks like a somewhat redundant use of arguments to me.
Things start to get confusing when $y_j=hF(t_{j-1},hy_{j-1})$ (where $h$ is the distance between any two adjacent $t_i$ and $y_i$ is the $i$th point computed by the Euler method) and they get even more confusing when
$$y''(t)=F'(t)=\frac{\Delta F}{\Delta t}(t,(y(t))+\frac{\Delta F}{\Delta y}(t,(y(t))F(t,(y(t))$$ (what is the $F(t,(y(t))$ doing here?)
and $F(t+\frac{h}{2}, y+\frac{h}{2}F(t,y))$ (this term came up like 2 lines later when we suddenly dealt with the Runge-Kutta-method)
I'm really having difficulties with the last two equations because I have no idea what to think of this $F$ and thus don't know what it is going to output when given a linear approximation (like in the latter equation).
Comment: In the wikipedia link $F$ is any function from a subset of $\mathbb R^n$ to whatever the codomain of $y$ is.
Comment: That still leaves me without a clue what the last term (and others) means though, isn't there any intuitive explanation what the single arguments are for?
Answer: An explicit  first-order ODE is an equation of the form $y'=F(t,y)$ where $F$ is some (known) function. For example, if the ODE is $y'=y^2-2ty+e^t$, then we write $F(t,y)=y^2-2ty+e^t$.
To solve this ODE means to find a function $y$ of variable $t$ such that $$y'(t) = F(t,y(t))\quad \text{for all } t$$
What is $y(t)$ doing here? It's the second argument of $F$, by the design of this ODE. What else would you put as the second argument of $F$?
When we try to solve this equation numerically, the variable $t$ runs through a discrete set of values $t_j$, and we look for $y_j$, approximate value of $y$ at $t_j$. A crude method is to pretend $F(t,y(t))$ is constant on the interval $[t_j,t{j+1}]$, so that
$$y_{j+1}=y_j+hF(t_j,y_j) $$
This isn't very precise, so a more sophisticated method is introduced, which takes the rate of change of $F$ into account. Being a function of two variables, $F$ responds to the changes of $t$, and also to the changes of $y$. This is accounted for by $\frac{\Delta F}{\Delta t}$
and $\frac{\Delta F}{\Delta y} F$

I'm really having difficulties with the last two equations

Equations are not supposed to make  sense. Unless they are framed by sentences that express the mathematical reasoning behind those equations. Are there any such sentences in the book? Did the professor say anything at all while writing those formulas? I hope yes. Those would be the clues to understanding.
Comment: Thank you very much! Finally I have an idea of what $F$ looks like! The last equation makes perfectly sense now and the second last the problem reduced to the question why there's an $F$ after $\frac{\Delta F}{\Delta y}$ and not after $\frac{\Delta F}{\Delta t}$, but I guess this has something to do with $y$ being a vector. However, this is not part of the original question anymore.
Comment: @"Are there any such sentences in the book? Did the professor say anything at all while writing those formulas?"
There aren't any explanations in the book and I couldn't attend the lecture (as well as multivariate calculus which might explain the above problem) because I had to do alternative service. Maybe he said something in the lectures, but my fellow students didn't have a clue either.


Replicate CSS3 sliding content transitions with jQuery

Question: A project I'm on is happy with the modern code I've developed using CSS3 (below) but want the same effect across two legacy browsers, IE8 (used in my client's office) and IE9. I've tried using the jQuery .animate function (an example below) but I'm wondering whether I'm doing something wrong - jQuery isn't something I normally use! I also know they require it to work with jQuery 1.3.2, which is what's used on the rest of their site, as they've had issues with more modern bits of jQuery breaking other functionality on the pages.
Here is the CSS
<code>#sliderOne .content,#sliderOne .image{position:absolute;top:0;left:180px;-webkit-transition:all .8s;-o-transition:all .8s;transition:all, .8s;-moz-transition:all .8s ease-in}
#sliderOne:hover .image{position:absolute;left:0}
#sliderThree .content,#sliderThree .image{position:absolute;top:180px;left:180px;-webkit-transition:all, .8s;-moz-transition:all .8s ease-in;-o-transition:all, .8s;transition:all, .8s}
#sliderFour .sliderTitle{position:absolute;top:0;left:0}
#sliderFour .content,#sliderFour .image{position:absolute;top:0;left:0;-webkit-transition:all, .8s;-moz-transition:all .8s ease-in;-o-transition:all, .8s;transition:all, .8s}
#sliderFive .sliderTitle{position:absolute;top:0;left:180px}
#sliderFive .content,#sliderFive .image{position:absolute;top:0;left:180px;-webkit-transition:all, .8s;-moz-transition:all .8s ease-in;-o-transition:all, .8s;transition:all, .8s}
.sliderTitle .right{text-align:right}
.sliderTitle p.number{font-size:6em}
.sliderTitle p.number,#sliderContainer h3,#sliderContainer h4{font-family:cursive}
#sliderContainer .content p,#sliderContainer .content h4{padding:1em}
#sliderOne,#sliderThree,#sliderFive,#sliderOne .content,#sliderThree .content,#sliderFive .content{float:left}
#sliderOne:hover .content,#sliderThree .sliderTitle{position:absolute;top:180px;left:180px}
#sliderTwo .sliderTitle,#sliderSix .sliderTitle{position:absolute;top:180px;left:0}
#sliderTwo .content,#sliderTwo .image,#sliderSix .content,#sliderSix .image{position:absolute;top:180px;left:0;-webkit-transition:all, .8s;-moz-transition:all .8s ease-in;-o-transition:all, .8s;transition:all, .8s}
</code>
And here's an example of the jQuery I've tried:
<code>    $('#sliderTwo').hover(function() {
  $('#sliderTwo .image').animate({top:'=-180px'},600);
});
</code>
I can provide some of the HTML as well if necessary.
Comment: Please make your CSS readable and explain clearly exactly what animation effect you are trying to achieve
Answer: I'm guessing you want something like THIS DEMO?
<code>$('#sliderTwo').mouseenter(function() {
  $('#sliderTwo .image').stop().animate({top:'0px'},600);
}).mouseleave(function() {
  $('#sliderTwo .image').stop().animate({top:'180px'},600);
});
</code>
Works in 1.3.2


create image from hard disk without free space (linux)

Question: I want to create image from hard disk without free space (useless space) in linux(ex3 type).
I've been tried to create image with dd command but this command gave us total size of hard disk.
I need data on this hard disk without free space.
thanks a lot.
Answer: One option would be to create the file system image as a sparse file. You could first run an utility such as zerofree on your ext3 file system to make sure all free blocks are filled with zeros, and then just image the disk with dd and pipe the image through cp with the --sparse=always option to force it to create a sparse file:
dd if=/dev/whatever | cp --sparse=always /dev/stdin disk.image

Comment: I had not actually done anything like this before, but I did test the idea with a dummy ext3 file system image before posting, and it seems to work. If `dd` had an option to create sparse files, the `cp` trick would be unnecessary. Apparently such an option was proposed a couple of years ago, but since the man page does not mention it, I assume the patch was not accepted: http://email@example.com/msg11795.html
Comment: This is just crazy enough to work.  I wouldn't have thought of piping the byte stream through cp.  Have you done this before or are you anticipating that it will work?
Answer: Sounds like Partimage might be what you are looking for?
Comment: For a filesystem-agnostic solution, you can fill the filesystem with nulls ("dd if=/dev/zero of=/some/file ; rm /some/file") and then use dd's "conv=sparse" option.  The downsides are: 1) This will be less efficient than a tool which knows the filesystem; and 2) so far as I can tell, using anything other than dd's default 512-byte block size will cause this to not work (or at least miss enough sparse space as to be useless), which will dramatically increase the time for dd to do its job.
Comment: I use Partimage and this is the best way to go.
Comment: @GeoffFritz 3) This won't work when any of the filesystems that the image needs to reside on or be transported via don't support sparse files.
Comment: no ext4 support tho
Answer: If you're using LVM, clonezilla is the way to go.
Answer: +1 Partimage .  The system rescue CD might help if you just want to save something.  Plug in a removable drive and/or a network mount once it has booted and write the image to disk.
If you're trying to image an entire drive for transport, don't forget to save the partition table (and the boot sector for a bootable)
Answer: I use partimage for get image also this program worke with command.
If you get image by bash script you work with this and dumpe2fs or xfsdump commands.


How to print out planes by airline

Question: Hey im using a hashmap of string and flights to create a flight store called planeStore.  So then i made another store(Airline store) also using a hashmap. I put the planeStore into the AirlineStore.  But i cant get the airlines printing out with the planes.
I thought by putting string airlineName into Airlines constrcutor. And passing in "Plane Name"  When creating Airline airline = new Airline("PlaneName"); that this would work but it hasnt.
here is my code:
Airline
import java.util.HashMap;

public class Airline
{
    private String airlineName;
    private HashMap<String, PlaneStore> map;

    public Airline(String airlineName)
    {
        this.airlineName = "";
        map = new HashMap<String, PlaneStore>();
    }
    public void add(PlaneStore plane)
    {
        map.put(airlineName, plane);
    }
    public void remove(String flight)
    {
        map.remove(flight);
    }
    public void printPlane()
    {
        System.out.println("\n********Flight List********");
        for (PlaneStore plane: map.values()) {
             //System.out.println(plane);
            // class
            // or:
            System.out.println(airlineName);
            System.out.println(plane.toString());

        }

    }

}

plane.toString is the toString of the PlaneStore:
public String toString() {
        return "PlaneStore [airlineName=" + airlineName + ", planeMap="
                + planeMap + "]";
    }

MainApp
import java.util.Scanner;

public class MainApp
{
    private Scanner keyboard = new Scanner(System.in);
    public static void main(String[] args)
    {
        new MainApp().start();
    }

    public void start()
    {
        Airline airline1 = new Airline("AerLingus");
        Airline airline2 = new Airline("Ryan Air");
        PlaneStore planeStore = new PlaneStore("Aer Lingus");
        PlaneStore planeStore2 = new PlaneStore("Ryan Air");

        Flight p1 = new Flight("Aer Lingus","A01", 150.5, 10.5, 500, Flight.AIRPLANETYPE.AIRBUS);
        Flight p2 = new Flight("Aer Lingus","B01", 50.3, 1.5, 91, Flight.AIRPLANETYPE.CORPORATE);
        Flight p3 = new Flight("Aer Lingus","C01", 12.2, -3.1, 56, Flight.AIRPLANETYPE.AIRBUS);

        Flight p4 = new Flight("Ryan Air","D01", 10.5, 1.5, 430, Flight.AIRPLANETYPE.PRIVATE);
        Flight p5 = new Flight("Ryan Air","E01", 0.3, 2.1, 101, Flight.AIRPLANETYPE.CORPORATE);
        Flight p6 = new Flight("Ryan Air","F01", 2.2, -3, 291, Flight.AIRPLANETYPE.AIRBUS);
        planeStore.add(p1);
        planeStore.add(p2);
        planeStore.add(p3);
        planeStore.print();

        airline1.add(planeStore);
        airline1.add(planeStore);
        airline1.add(planeStore);
        airline1.printPlane();

        planeStore2.add(p4);
        planeStore2.add(p5);
        planeStore2.add(p6);

        airline2.add(planeStore2);
        airline2.add(planeStore2);
        airline2.add(planeStore2);
        airline2.printPlane();

    }

}

Comment: is the airlineName ever assigned to anything other than ""?
Comment: It looks like you are not using your map keys. So you should use a java.util.List instead of a Map
Answer: You're setting airlineName to "" rather than the String that you pass into it throught the constructor.
Answer: Your Airline construtor receives a String argument but you are not assignment the instance variable airlineName of the class Airline to this argument. You are just making airlineName set to "".
public Airline(String airlineName)
    {
        this.airlineName = "";
        map = new HashMap<String, PlaneStore>();
    }

you mean:
public Airline(String airlineName)
        {
            this.airlineName = airlineName;
            map = new HashMap<String, PlaneStore>();
        }

Looking further in your code, it appears that each Airline class will have an map but you only add a key to this map, along with the values PlaneStore. So it appears that you will never have two or more keys for each map on each Airline class. Therefore, there is no point in using map, you can use instead an ArrayList.
If I understand correctly your objective you can simplify your AirLine class to something like this:
public class Airline
{
    private String airlineName;                // Name of the company
    private ArrayList <PlaneStore> planeStore;

    public Airline(String airlineName)
    {
        this.airlineName = airlineName;
        map = new ArrayList<PlaneStore>();
    }
    public void add(PlaneStore plane){ planeStore.add(plane);}

    public void printPlane()
    {

        System.out.println(airlineName);
        System.out.println("\n********Flight List********");
        for (PlaneStore plane: planeStore)
        {
            System.out.println(plane.toString());
        }

    }

}
Answer: Once you change the code to read this.airlineName = airlineName; you should be ok with this part.
By the way it still looks like you are using the same key for every plane you add. This will constantly overwrite the last plane you added with the new one. If you want to be able to print out all of the planes, you need to give them each a unique key. Otherwise this won't work.

How to print out planes by airline


:first-child selector not working on li (list item)

Question: JSfiddle: https://jsfiddle.net/iqbal98/rxp0dxm9/
Issue: Select first instance of the class search-result-group-posts
In this case ul has many li or called .search-result-item too, but specifically on
li.search-result-item.search-result-group-posts

I want the first of this li's to have a different background-color and a margin-left
This is what I want: https://jsfiddle.net/iqbal98/rxp0dxm9/1/ (html inline css added)
PD:

look at /*DOES NOT WORK*/ comment section to quickly see the problem
I'm using Sass and the :first-child selector is used this way: &:first-child. I also tried in a separated way (without the "&")

li.search-result-group[data-search-group=posts]{
        border-bottom-width:0;
      }
      .search-result-group-posts:first-child{
        margin-left:10%;/*DOES NOT WORK*/
        background-color:red;/*DOES NOT WORK*/
      }
      li.search-result-item.search-result-group-posts{
        position:relative;
        border:1px solid brown;
        display:inline-block!important;
        width:29.478%;
        border-radius:4px;
        margin:0 5px;
        .search-result-post-up{
          font-size:16px!important;
          border-radius: 10px;
          padding:4px;
          .search-result-post-title{
            margin-left:3%;
            font-size:110%!important;
          }
          .search-result-post-content{
            white-space:normal!important;
            margin:.3% 2% .7% 2%;
            font-size: 70%!important;
            text-align:justify;
          }
        }
      }

Posts

        Lorem Ipsum

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eget egestas est, consequat consequat nibh.

        Lorem Ipsum

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eget egestas est, consequat consequat nibh.

        Lorem ipsum

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eget egestas est, consequat consequat nibh.

Categories

category-1

category-2

Favorites

favorite-1

favorite-2

favorite-3

Keywords

keyword-1

keyword-2

keyword-3

keyword-4

Comment: `search-result-group-posts` is not the first child; there is the `Posts` `` that comes first
Comment: @iqbal_cs you need to give it a class or find some sort of workaround, there isn't a `:first-of-class` selector yet in CSS. http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class
Comment: @kittykittybangbang's answer is why it isn't working. That element isn't the "first child" of it's parent - it's the first instance of that class. Those are 2 different things.
Comment: One problem is that you're trying to use SCSS without specifying that in the Fiddle.
Comment: using SCSS on jsfiddle just adds some styles to the result
Comment: @Michael Coker how can I select the first instance of a class? I tried both `first-of-type` and `first-child`
Comment: Here: https://www.w3schools.com/cssref/tryit.asp?filename=trycss_sel_firstchild is selecting first instance of `p` (inside the `body`). Am I wrong?
Comment: Please post your "*[mcve]*" code (including the relevant HTML) in your question, otherwise if, or when, JS Fiddle (or any other external site) fails this question will become useless to future visitors.
Answer: For those who want to select the first instance of a class, this is the syntax:
.the-class{
    background-color: red; /*APPLY TO ALL*/
}
.the-class ~ .the-class {
    background-color: none; /*CANCEL TO SIBLINGS*/
}

In my case, I added this above all the SCSS code in the initial jsfiddle:
.search-result-group-posts{
    background-color: red;
}
.search-result-group-posts ~ .search-result-group-posts {
    background-color: none;
}

Good lesson learned today...


Function in views tpl

Question: How can I add a function  in my custom views .tpl page or where can I write my function and call that function in my views .tpl ?
Answer: You can write the function in any php file that gets loaded.  PHP is not sequential in loading/processing files, it will load them first then process.
Comment: You _can_, but you probably shouldn't. Keeping some sort of structure would be preferable
Answer: For the sake of any future developer, including yourself, you should try to keep your custom functions inside your template.php file or in a module that you've created.
that is where people will expect to find functions used in templates and such.
Comment: This. A thousand times this :) Anyone who's inherited a site from a dubious developer will agree I'm sure
Answer: Data transformation or processing should go in the preprocess function for that template. That way the template stays neat and only focused on presentation. In the preprocess function you can alter, remove, or add new variables as you please. These variables will then be available in the associated template. As user5482 mentions, it should go in either your theme's template.php, or in a custom module. If you are only altering or removing a variable, then your template.php will suffice. If you are creating new variables with data not readily available it should probably go into a new module and an earlier hook in the pipeline.
Make sure to document your new variable in the template as that is the first place where themers will look for information about it.

Function in views tpl


Como eu posso adicionar 2 botões com submenu no Android Studio

Question: Gostaria de adicionar de forma dinâmica opções ao menu da minha tela no Android, eu vi diversos exemplos, mas todos voltados para um unico botão.
supondo que eu tenha.
 override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
        menu.clear()

       val menu1 = menu
                .add(Menu.NONE, 1, Menu.NONE, null)
                .setIcon(R.drawable.ic_add_round_white)
               .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

        val menu2 = menu
                .add(Menu.NONE, 2, Menu.NONE, null)
                .setIcon(R.drawable.ic_edit_white)
                .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

}

nesse exemplo eu consigo gerar 2 botões ao barra superior da minha tela, a dúvida é como incrementar opções dentro desses botões?
eu utilizo kotlin, mas java ja resolveria.
Comment: Não é melhor você criar o layout no `menu.xml` e sobrescrever o método `onPrepareOptionsMenu` mudando apenas a visibilidade dos itens que deseja que apareça?
Comment: Não, porque as opções são baseadas no que a API me fornece, que podem mudar dinamicamente ;(
Answer: É possível de ser feito sim. Tanto por XML quanto programaticamente.
Recomendo dar uma olhada a fundo na documentação do Android sobre menus: https://developer.android.com/guide/topics/ui/menus?hl=pt-br
Para criar os submenus você terá que assosiar estes teus dois MenuItem como sumbenus e adicionar novos itens a eles:
override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) {
    menu.clear()

   val menuItem1 = menu
            .add(Menu.NONE, 1, Menu.NONE, null)
            .setIcon(R.drawable.ic_add_round_white)
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

   val subMenu1 = menu.addSubmenu(
                  groupid = 1,
                  itemId = menuItem1.itemId,
                  order = 1,
                  title = "Título")

   val subItem1 = subMenu1
            .add(Menu.NONE, 11, Menu.NONE, null)
            .setIcon(R.drawable.ic_add_round_white)
            .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM)

}

PS: Nomeei os parâmetros na função addSubmenu para ilustrar os parâmetros, não é necessário tê-los assim.
Aí você repete com os outros itens. Entretante recomendo fortemente fazer isso usando menus em XML e inflar da acordo com a necessidade. Pois é muito mais fácil dar manutenção nesse tipo de código pois a construção fica muito mais simples e dividida em camadas.
Comment: Eu entendi o seu exemplo, mas nesse caso como eu poderia também acrescentar um menu de opções ao primeiro botão, nessa parte que boio. Precisa ser programaticamente pois as opções vem fornecidas pela API, baseado no acesso, resumindo são 2 botões na action bar e esses 2 botões possuem varias opções.


how to create page visiter counter in codeigniter?

Question: I want to create page view counter when customer visit our website. How can I code it in codeigniter ?

Answer: You may want to see this post Hit Counter in Codeigniter
and also Codeigniter: how to do hit counter for each news
to know more you need to visit
http://webeasystep.com/blog/view_article/how_to_build_unique_visitors_counter_with_codeigniter
Hope thats helps.