Capturar imagens da webcam a cada 1 segundo usando JavaCV

Question: Um determinado programador está fazendo um projeto em que a webcam padrão tira fotos a cada 1 segundo utilizando o JavaCV.
Por enquanto ,nesse code, ao clique do botão capturar ele captura uma foto e salva na pasta do programa. Pede-se que o programa salve as fotos em uma determinada pasta selecionada pelo usuário e que a webcam capture fotos a cada 1 segundo.
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_highgui;
import com.googlecode.javacv.cpp.opencv_highgui.CvCapture;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);

JOptionPane.showMessageDialog(null, "Aperte a tecla P para parar a gravação");
        while(KeyEvent.VK_P){

try{
            grabber.start();

IplImage img = grabber.grab();

            if(img!=null){
                cvSaveImage("image1.jpg", img);
            }
        }
        catch(Exception e){
         e.printStackTrace();
        }
        setFocusable(true);
        setVisible(true);

        }

Answer: Você pode utilizar a classe Timer para isso.
Só basta criar um Timer, e setar um TimerTask que faça o que você precisa dentro do método run(), por exemplo:
Timer timer;

public void criarTimer(int segundos) {
    TimerTask timerTask = new TimerTask() {
        public void run() {
            System.out.println("Time's up!");
        }
    };
    int segundosParaComecar = 0;
    int segundosParaCapturar = segundos*1000;
    timer = new Timer();
    timer.schedule(timerTask, segundosParaComecar, segundosParaCapturar);
}

Veja funcionando no IdeOne.
E outra coisa. Se precisar cancelar o timer, eu aconselho a deixar uma variavel global, e fazer uma condição dentro do run() do TimerTask, assim você pode dar um timer.cancel() quando quiser.


Cannot assign Label to Listcell

Question: I want to assign a string as label to Listcell which ends with these ascii  characters       32 and 0 i.e space and null, but when I try to assign it it my Listcell I get an unterminated string constant error. right now I am doing str.trim() on that string to assign it as label to my listcell. I there any other way to do so, with out altering the string? I am doing this in ZK
Comment: Can you post the code you are using?
Answer: <code><listitem self="@{each=Item}" label="@{Item.yourStringValue, converter='your.company.StringConverter'}"/>
</code>
Create a class your.company.StringConverter which implements org.zkoss.zkplus.databind.TypeConverter
Implement public Object coerceToUi(Object val, Component comp) in such a way that it will do on-the-fly conversion.
This approach would not affect your internal data structures, only their representation in ZK ui.

Cannot assign Label to Listcell


Agrupamento de linhas incorreto

Question: Olá alguém consegue me ajudar, eu estou tentando trazer um relatório de empresa e atividade feitos em 12 meses, uma empresa e uma atividade foi feita durante 12 meses e quero saber de cada atividade se ela foi feita em janeiro, fevereiro,  março etc, o problema é que não esta agrupando por empresa corretamente o mês a mês.
Meu código.
SELECT
empresas,
tipo_atividade,
CASE WHEN MONTH(dt_fim) = '1'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_1,
CASE WHEN MONTH(dt_fim) = '2'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_2,
CASE WHEN MONTH(dt_fim) = '3'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_3,
CASE WHEN MONTH(dt_fim) = '4'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_4,
CASE WHEN MONTH(dt_fim) = '5'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_5,
CASE WHEN MONTH(dt_fim) = '6'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_6,
CASE WHEN MONTH(dt_fim) = '7'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_7,
CASE WHEN MONTH(dt_fim) = '8'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_8,
CASE WHEN MONTH(dt_fim) = '9'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_9,
CASE WHEN MONTH(dt_fim) = '10'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_10,
CASE WHEN MONTH(dt_fim) = '11'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_11,
CASE WHEN MONTH(dt_fim) = '12'   THEN IFNULL('OK','PENDENTE')  ELSE  'PENDENTE' END AS MES_12

FROM tbl_atividades
WHERE
YEAR(dt_fim) = '2019' AND
(STATUS = 'CONCLUIDO' OR STATUS = 'CONCLUIDO_VENCIDO')
ORDER BY empresas, tipo_atividade;

O resultado é o seguinte

Quando uso a clausula GROUP BY EMPRESAS o resultado fica errado.

Também tentei
GROUP BY EMPRESAS
GROUP BY EMPRESAS, TIPO_ATIVIDADE
GROUP BY TIPO_ATIVIDADE

Todos deram errado , o que eu preciso fazer para exibir corretamente por empresa e atividade no mes a mes em uma única linha.
Comment: Você tem que especificar uma função de agregação.
Answer: Uma das maneiras de resolver isso seria contando quantos registros tem dt_fim no mês correspondente e atendem aos outros critérios do WHERE, depois de chegar nesse valor, você verifica se existe algum registro naquele mês, se existir, preenche com OK, caso contrário PENDENTE, algo do tipo:
SELECT
  empresas,
  tipo_atividade,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 1 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_1,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 2 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_2,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 3 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_3,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 4 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_4,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 5 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_5,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 6 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_6,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 7 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_7,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 8 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_8,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 9 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_9,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 10 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_10,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 11 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_11,
  CASE WHEN (SUM(CASE WHEN MONTH(dt_fim) = 12 THEN 1 ELSE 0 END)) > 0 THEN 'OK' ELSE 'PENDENTE' END AS MES_12
FROM
  tbl_atividades
WHERE
  YEAR(dt_fim) = '2019' AND (STATUS = 'CONCLUIDO' OR STATUS = 'CONCLUIDO_VENCIDO')
GROUP BY
  empresas, tipo_atividade;

O SUM(CASE WHEN MONTH(dt_fim) = 1 THEN 1 ELSE 0 END) faz a contagem que eu informei.

Agrupamento de linhas incorreto


How does this limit ove the Binomial distribution behave?

Question: My professor has given me the following exercise:

Assume $p \in \left(0,1\right)$ and
$n \in \mathbb{N}^{+}$ and then consider $X_{n} \sim \operatorname{Bi}\left(n,p\right)$
(Binomial Distribution with parameters $p$ and $n$).
Then, what is the value of $\lim_{n\to\infty} P\left(X_{n} \le\frac n4\right)?$

The only attempt I have found simply states that if $n$ approaches infinity so does $\frac n4$ and therefore the probability must be $1$. However, I'm not sure that is the correct reasoning for this excersise.
EDIT: I'm actually not asked about the value for the limit, but for an approximation of $P\left(X_{n} \le\frac n4\right)$ for a large enough value of $n$.
Comment: I don't know if this is correct at all, but if I denote $Y_{i} \sim Bernouilli(p)$ I have that $\sum_{i=1}^n Y_{i} \sim X_{n}$ and $\lim_{i\to\infty} \frac{1}{n} \sum_{i=1}^{infty} Y_{i} \rightarrow p$ and so for n that is big enough I can assume that $Y_{n}$ is similar to a distribution that follows $P(Z=np) = 1$ and so if $p \leq \frac{1}{4}$ the probability is 1 and it'd be 0 in the opposite situation. I must add that I'm not actually asked about the value of the limit but for an approximation of $P(X_{n} \leq \frac{n}{4})$ for a "big" value of n.
Comment: Yes you are right, and I know that reasoning isn't correct, but using the probability function of $Bi(n,p)$ isn't helping either.
Comment: https://en.wikipedia.org/wiki/Law_of_large_numbers
Comment: So I have to study  $\lim_{n\to\infty} \sum_{i=1}^{\lfloor \frac{n}{4} \rfloor} \binom{n}{i}p^{i}(1-p)^{n-1}$
Answer: One important fact to keep in mind when working with binomial distributions is that they are essentially sums of "smaller" binomial distributions, meaning for $X\sim\text{Bin}(n,p)$ and independent variables $Y_1,\dots,Y_n\sim \text{Bin}(1,p)$ we have: $$X\stackrel{d}{=}\sum_{i=1}^n Y_i$$
The intuition for this is that no matter if you flip one coin $n$ times and add up the number of heads or whether you flip $n$ coins once and look at the number of heads, you should expect the same distribution of the number of heads in both cases.
We can use this to rewrite the given quantity as $$\mathbb P[X_n\leq \frac{n}{4}]= \mathbb P\bigg[\sum_{i=1}^n Y_i\leq \frac{n}{4}\bigg]=\mathbb P\bigg[\frac{1}{n}\sum_{i=1}^n Y_i\leq \frac{1}{4}\bigg]$$
The term $\frac{1}{n}\sum_{i=1}^nY_i$ should remind you of something.
Comment: Yes that is what I have been using, but now my question is: shoud I use the fact that $\overline{Y}$ converges to $p$ by LLN and then use that for my approximation, or should I instead use that $\overline{Y} \rightarrow \mathcal{N}(p,\frac{p(1-p)}{n})$ by CLT?
Comment: @jaimejdtrechuelo Both are valid approaches, though i think the LLN is the simpler choice here.
Comment: That's what I thought, appreciate it


How to test if those 2 regression models are fundamentally equivalent?

Question: I want to test/prove if two regressions are fundamentally the same thing.
But first, make this a reproducible example.
Create the levels for each factor variable
levels_a <- c("A1", "A2", "A3", "A4")
levels_b <- c("B1", "B2", "B3")
levels_c <- c("C1", "C2")

Generate all possible combinations of factor levels
combinations <- expand.grid(levels_a, levels_b, levels_c)

Create a data frame with the factor variables and the dependent variable
data <- data.frame(
  a = factor(combinations$Var1),
  b = factor(combinations$Var2),
  c = factor(combinations$Var3),
  DepVar = sample(c(0, 1), size = nrow(combinations), replace = TRUE)
)

My original regression is
original <- glm(formula = DepVar ~ a*b*c , family = "binomial",
            data = data)
summary(original)

A, B and C are all factors. A has four levels, b has three levels, and c has 2 levels.
Therefore, the "original" regression has an intercept and  3 terms from a, 2 terms from b, 1 term from c, then 6 (3*2) from a and b, and then, lastly, 11 terms from c (c= 1 times all before but itself).  In sum, these are 23 terms plus intercept. However, I want to use the sjplot for interactions, and this packet only allows one interaction. I want to plot the c- to the rest- interaction. So I thought maybe I could do it like this:
My second regression is
data$interaction_var <- interaction(data$a,  data$b)

test <- glm(formula = DepVar ~ interaction_var * c , family = "binomial",
                             data = data)
summary(test)

While this interaction can be plotted with "sj", I want to find out if this regression always produces the same predicted values as the first regression, as this regression has different terms:
Again, it has an intercept, all 12 interactions (minus 1) from a and b, 1 from c, and again 11 (c=1 times everything so far but itself). So, it also has 23 components.
How can I show that they are identical in terms of predictions?
Answer: You asked

How can I show that they are identical in terms of predictions?

If you just want a computational demonstration (rather than a mathematical proof),
all.equal(predict(original), predict(test))

should do it ... (all.equal() automatically uses an "equivalent within numerical tolerances" test, rather than testing that the two predictions are identical up to the full floating-point precision).
You did say

always produces the same predicted values

[emphasis added] (not "produces the same predicted values for the original data set"), but something pretty weird would have to be happening (or you'd have to pick a pathological data set) in order for the predictions to be identical on the training set but different for some other set of input.
Answer: I suppose that the models will be identical and produce equal predicted values if they have same coefficients:
epsylon <- 10^-6 # set maximum allowed difference between coefficients
length(coefficients(original)) == length(coefficients(test)) &&
all(abs(coefficients(original) - coefficients(test)) < epsylon
)

[1] FALSE

And we can print different coefficients in a human readible form:
data.frame(coefficients(original),
           coefficients(test))[
               abs(coefficients(original) - coefficients(test)) >= epsylon,
               ]

            coefficients.original. coefficients.test.
bB3                  -5.113214e+01       3.246735e-09
cC2                   1.014892e-07      -5.113214e+01
aA2:bB2               5.113214e+01       1.029394e-07
aA3:bB2              -4.707198e-09      -5.113214e+01
aA4:bB2              -1.057436e-07      -5.113214e+01
aA2:bB3               5.113214e+01       5.457133e-09
aA3:bB3               1.022643e+02       5.717070e-10
aA4:bB3               5.113214e+01      -1.227631e-09
bB3:cC2               5.113214e+01      -5.113214e+01
aA2:bB2:cC2          -5.113214e+01       1.227629e-09
aA3:bB2:cC2           5.113214e+01      -9.859460e-08
aA2:bB3:cC2          -1.022643e+02       1.227591e-09
aA3:bB3:cC2          -5.113214e+01      -2.211011e-06
aA4:bB3:cC2          -1.022643e+02      -5.113214e+01

Comment: Comparing the coefficients is relevant *only* when the variables are coded identically in both models.  Why not just compare the predictions to each other?
Comment: I think all the variables a, b, and c are the same, so they are also "coded identically". I use the same variables from the same dataset.


How to find fundamental groups and covering spaces of $\mathbb{RP}^2\vee \mathbb{RP}^2$?

Question: The following is an exercise I was assigned in homotopy theory.
Defined $X = \mathbb{RP}^2\vee \mathbb{RP}^2$.
a) Find $\pi_1(X)$.
b) Find the universal cover of $X$.
c) Find all of its connected $2$-sheeted covers.
I am trying to use van Kampen's theorem for (a).
I decompose $X$ into two open sets $U_1$ and $U_2$, where each $U_i$ contains one copy of $\mathbb{RP}^2$ as well as a neighborhood around the point of attachment small enough so that each $U_i$ deformation retracts onto the copy of $\mathbb{RP}^2$ that it contains.
Then van Kampen's theorem gives that $\pi_1(X)$ is a quotient of $\mathbb{Z}_2*\mathbb{Z}_2$, where we quotient out by the subgroup normally generated by the elements $\iota_{1, 2}(\omega)\iota_{2, 1}(\omega)^{-1}$, where $\iota_{1, 2}: \pi_1(U_1 \cap U_2) \to \pi_1(U_1)$ is the inclusion map, and similarly for $\iota_{2, 1}$, and the $\omega$'s are arbitrary elements of $\pi_1(U_1 \cap U_2)$.
I want to say that $U_1 \cap U_2$ is simply connected, so each $\iota_{1, 2}(\omega)\iota_{2, 1}(\omega)^{-1}$ is in fact trivial, so then $\pi_1(X)$ is isomorphic to $\mathbb{Z}_2*\mathbb{Z}_2$. Is this true, or did my reasoning go awry somewhere?
For (b), I know that the universal cover is just an infinite chain of copies of $S^2$, where the covering map is just ``locally'' the quotient map.
For (c), I know that the only covering spaces of $\mathbb{RP}^2$ is itself and $S^2$, but I don't really know how to go from there to finding all the connected $2$-sheeted covers.
To summarize: is in fact $\pi_1(X)$ isomorphic to the free product of two copies of $\mathbb{Z}_2$, and how do I find all connected $2$-sheeted covers of $X$?
Answer: Everything you've said is correct (to prove $U_1\cap U_2$ is simply connected, just note that you can separately deformation-retract the part of it in each $\mathbb{RP}^2$ down to the basepoint to show it is contractible).  For part (c), you can use some group theory.  By the correspondence between connected covers and subgroups of $\pi_1$, the 2-sheeted covers correspond to index 2 subgroups of $\mathbb{Z}_2*\mathbb{Z}_2$.  Any index two subgroup of a group is normal, so such subgroups are exactly the kernels of epimorphisms $\mathbb{Z}_2*\mathbb{Z}_2\to\mathbb{Z}_2$.  Such epimorphisms are easy to classify by the universal property of free products: a homomorphism $\mathbb{Z}_2*\mathbb{Z}_2\to\mathbb{Z}_2$ is just a pair of homomorphisms $\mathbb{Z}_2\to\mathbb{Z}_2$, each of which is either trivial or an isomorphism.  Such a homomorphism is surjective iff at least one of the homomorphisms $\mathbb{Z}_2\to\mathbb{Z}_2$ is nontrivial.
This gives that there are three index two subgroups: the kernels of the homomorphisms $f,g,h:\mathbb{Z}_2*\mathbb{Z}_2\to\mathbb{Z}_2$ given by $f(a)=1$, $f(b)=0$, $g(a)=0$, $g(b)=1$, and $h(a)=1$, $h(b)=1$ (where $a$ and $b$ are the two generators of $\mathbb{Z}_2*\mathbb{Z}_2$).  You can then get the covering spaces as the quotients of the universal covering space by these subgroups acting as deck transformations.  More explicitly, the covering coming from $\ker(f)$ is $S^2$ (mapping to the first $\mathbb{RP}^2$) with two copies of $\mathbb{RP}^2$ (mapping to the second $\mathbb{RP}^2$) attached to it at two antipodal points.  The covering coming from $\ker(g)$ looks the same, just with the roles of the two $\mathbb{RP}^2$s in $X$ swapped.  The covering coming from $\ker(h)$ is two copies of $S^2$ attached at two antipodal points.


Eigenvalues of $A + \mu I$

Question: Strang's Linear Algebra 4th edition, page 306, example 6.2B asks to find the eigenvalues of the following matrix:
$$ A = \begin{bmatrix}5&&&\\&5&\\&&5\\&&&5\\\end{bmatrix} - \begin{bmatrix}1&1&1&1\\1&1&1&1\\1&1&1&1\\1&1&1&1\\\end{bmatrix} = \begin{bmatrix}4&-1&-1&-1\\-1&4&-1&-1\\-1&-1&4&-1\\-1&-1&-1&4\\\end{bmatrix} $$
I understand why the eigenvalues of the first matrix are $\{5,5,5,5\}$ and of the second are $\{4,0,0,0\}$.
But then he finds the eigenvalues of $A$ by pairwise subtracting them, resulting in $\{1,5,5,5\}$.
Why could he do that? Previously in the chapter he wrote: "...the eigenvalues of $A + B$ are generally not $\lambda + \beta$."
Answer: The point is that in this case you're not adding just any matrices: one of them is a multiple of the identity.  $\lambda$ is an eigenvalue of $A$ if and only if $A - \lambda I$ is singular.  So this is also equivalent to: $\lambda + \mu$ is an eigenvalue of $A + \mu I$.
Comment: Thank you, I get it now. As $A- \lambda I$ being singular says that $\lambda$ is an eigenvalue for $A$, $A + \mu I - \lambda I - \mu I$ being singular says that $\lambda + \mu$ is an eigenvalue for $A + \mu I$.

Eigenvalues of $A + \mu I$


How can I exit from a javascript function?

Question: I have the following:
function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ...
    ...

I would like to exit from this function if an "if" condition is met. How can I exit? Can I just say break, exit or return?
Answer: if ( condition ) {
    return;
}

The return exits the function returning undefined.
The exit statement doesn't exist in javascript.
The break statement allows you to exit a loop, not a function. For example:
var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

This also works with the for and the switch loops.
Answer: Use return statement anywhere you want to exit from function.
if(somecondtion)
   return;

if(somecondtion)
   return false;

Answer: you can use
return false; or return; within your condition.
function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}

Answer: Use this when if satisfies
do
return true;

Answer: You should use return as in:
function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

Answer: I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
  return Browser.msgBox("something");
  }
}

This way you not only exit the function, but show a message saying why it stopped. Hope it helps.


Get data from Solr to JTable

Question: I new in Solr. I can add data to Solr from application, but I want to get data from Solr to my Java desktop application.
How can I get data from Solr ("http://localhost:8983/solr")?
Comment: [whathaveyoutried](http://whathaveyoutried.com)?
Answer: You probably want to use some solr client to requests and handle response data.
But you can do it in simple HTTP GET request if you want to like so:
// get all documents
http://localhost:8983/solr/select?q=*:*

If you're using multiple cores, then you probably need to use:
// get all documents from core0
http://localhost:8983/solr/core0/select?q=*:*

You can read more about solr common query parameters here.
Answer: Solrj is the easiest way to go. It's the solr java client library.
Add it as a dependency to your project, then write a pojo with all the fields that you want to get back from Solr. Annotate each field with the solrj @Field annotation, then send your query to Solr like this:
SolrServer solrServer = new HttpSolrServer("htp://localhost:8080/solr/core0");
QueryResponse response = solrServer.query(new SolrQuery(query));
List<Pojo> pojos = response.getBeans(Pojo.class);

Get data from Solr to JTable


Qual é a funcionalidade do método "heapify" do módulo heapq?

Question: Para que serve o método heapify da biblioteca heapq do Python? Como eu  poderia usá-lo em uma lista, por exemplo?
Comment: O `heapifiy` transforma a lista passada num heap. [Veja um exemplo de um heap na wikipedia por exemplo](https://pt.wikipedia.org/wiki/Heap). Pelo que eu vi seria especificamente um *min-heap* mas só confirmando na documentação/código.
Answer: Heap
Antes de perceber para que serve o método heapify tem de perceber como funciona um Heap. Pela documentação da HeapQ do Python vemos que a implementação usa um Heap Binário como min-heap.
Um heap desse gênero organiza-se como uma arvore binária, em que cada elemento pode ter um filho esquerdo e direito, e o menor elemento encontra-se no topo.
Ilustração deste princpio:

A regra para um min-heap é que um elemento pai tem de ser menor ou igual a um elemento filho. Num max-heap esta regra é precisamente o oposto.
A figura anterior é apenas um representação visual do que um heap é, ele no entanto é disposto num array, com uma organização especifica. Os elementos são dispostos, olhando para a arvore, de cima para baixo e da esquerda para a direita.
Seguindo essa regra o heap assim ilustrado ficaria assim num array:

Mas a mesma relação existe neste array, embora que implícita:

Para heaps com primeiro índice a 0 a formula para descobrir os filhos de um elemento é:
Filho Esquerda = 2 * i + 1
Filho Direita = 2 * i + 2

Em que i é a posição do elemento em questão.
Exemplificando para o elemento 17 que tem a posição 3:
Filho Esquerda = 2 * 3 + 1 = 7 => posição 7 que corresponde ao valor 25
Filho Direita = 2 * 3 + 2 = 8 => posição 8 que corresponde ao valor 100

Python
Passemos agora á utilização deste heap em python. Podemos começar por construir uma lista com os valores mostrados nas figuras anteriores:
lista = [100,3,2,17,19,36,1,25,7]

Agora ao chamarmos o método heapify esta lista irá ser transformada num heap com todas as características vistas anteriormente:
import heapq #necessário importar heapq

lista = [100,3,2,17,19,36,1,25,7]

heapq.heapify(lista)
print(lista) #[1, 3, 2, 7, 19, 36, 100, 25, 17]

Veja este exemplo no Ideone
Repare que a disposição em array não ficou exatamente igual ao ilustrado nas figuras anteriores, mas continua a ser um heap válido e equivalente.
Agora pode tirar partido do heap que tem e continuar a utilizar mais funções da biblioteca heapq. A titulo de exemplo podemos utilizar o heappop que remove e devolve o primeiro elemento do heap. Sendo este um min-heap o elemento a remover é o mais pequeno:
menor = heapq.heappop(lista)
print(menor) #1
print(lista) #[2, 3, 17, 7, 19, 36, 100, 25]

Veja este exemplo também no Ideone
Motivação
É bem possível que neste momento se questione do porquê de utilizar uma estrutura de dados como um heap binário. Pois bem, esta estrutura de dados oferece-lhe complexidade diferentes para a maior parte das operações, sendo algumas mais rápidas que as de uma lista.
Complexidade de tempo com notação O para um Heap binário:

Isto pode trazer-lhe vantagem dependendo do algoritmo que tem, e do seu objetivo.
Documentação para o heapify e para o heappop
Referencias:
Heap na wikipedia


Showing the uploaded image in Vaadin with EasyUploads

Question: I'm trying to use EasyUploads-addon for Vaadin, but can't get the image shown.
When I click addon's "Choose File"-button, it will ask me to open an file. I choose some .png -file from my images and addon shows the information of the picture beneath it.
Then I press my "Upload"-button, which is currently needed just to show the uploaded image at first.
private void showUploadedImage() {
    Object value = upload.getValue();
    byte[] data = (byte[]) value;

    StreamResource resource = new StreamResource(
            new StreamResource.StreamSource() {
                private static final long serialVersionUID = 1L;

                @Override
                public InputStream getStream() {
                    return new ByteArrayInputStream(data);
                }
            }, "filename.png");

    image.setVisible(true);
    image.setCaption("Uploaded image");
    image.setSource(resource);
}

upload = EasyUpload's component which is used to choose file
image = Embedded component that I have drawn with the designer to my layout.
But when I look the page with browser the image is not shown. The image is just shown as there is no image at all, just caption will be shown.
HTML-code of the image from the page's source:

This might be really trivial case, but all the examples that I found was over 3-4 years old and didn't look helpful.
Can someone tell me, how it should be done?
Comment: Your code does not compile. You need to make byte[] data final.
Answer: You need to call a setter on UploadField class:
uploadField.setFieldType(FieldType.BYTE_ARRAY);

Working SSCCE:
@Override
protected void init(VaadinRequest request) {
    setContent(layout);
    final UploadField uploadField = new UploadField();
    uploadField.setAcceptFilter(".png");
    uploadField.setFieldType(FieldType.BYTE_ARRAY);
    uploadField.addListener(new Listener(){
        @Override
        public void componentEvent(Event event)
        {
            showUploadedImage(uploadField);
        }
    });
    layout.addComponent(uploadField);
    layout.addComponent(image);
}

private void showUploadedImage(UploadField upload) {
    Object value = upload.getValue();
    final byte[] data = (byte[]) value;

    StreamResource resource = new StreamResource(
            new StreamResource.StreamSource() {
                @Override
                public InputStream getStream() {
                    return new ByteArrayInputStream(data);
                }
            }, "filename.png");

    image.setSource(resource);
}

Produces (after choosing a .png file):
Of course you may want to change type of uploadField listener to more specific one.
Tested on Java 8, Vaadin 7.4.1, Eclipse Luna.


aws.push to more than one environment

Question: I have two different environments running off of the same git repository.  it looks like in the AWS console tools for git and elastic beanstalk, I can only connect one environment at a time, is there anyway to have it push to both of my environments at the same time?
Answer: The latest version allows you to map different branches to different repositories, see Announcement: Deploy Git Branches to Multiple Elastic Beanstalk Environments:

Starting today, you can use eb and Git to deploy branches to multiple
  Elastic Beanstalk environments. You can also manage and configure
  multiple Elastic Beanstalk environments using eb. For example, you can
  configure eb and Git to deploy your development branch to your staging
  environment and deploy your release branch to your production
  environment. [...]

aws.push to more than one environment


Erro ao tentar utilizar o Local Storage do HTML5

Question: Estou estudando sobre local storage em HTML5 e JS, entendendo que seu proposito é o de armazenar textos no local storage do browser.
Ao testar, obtive erros de JS. Gostaria de entender melhor o porquê:

    <form>
        Nome: <input type="text" id="nome">
        <input type="button" onclick="salvar();" value="Save">
    </form>

Comment: Onde está seu método `salvar`? O erro é que ele não foi definido. Não há nenhum erro com o `localStorage`.
Answer: Faltou apenas definir a função SALVAR:

    <form>
        Nome: <input type="text" id="nome">
        <input type="button" onclick="salvar();" value="Save">
    </form>

Comment: Fiz um fiddle demonstrativo: http://jsfiddle.net/s7e53t3r
Comment: Ainda bem que faltou "apenas" isso :) ... +1
Comment: muito obrigado a todos.


App.config - custom section not working

Question: I recently started building a console version of a web application. I copied my custom sections from my web.config. to my app.config. When I go to get config information i get this error:
An error occurred creating the configuration section handler for x/y: Could not load type 'x' from assembly 'System.Configuration
The line that it is not liking is:
return ConfigurationManager.GetSection("X/Y") as Z;
Anyone run into something like this?
I was able to add
<add key="IsReadable" value="0"/>

in the appSettings and read it.
Addition:
I do actually have this defined about the custom section:
  <configSections>
    <sectionGroup name="x">

    </sectionGroup>

  </configSections>

Answer: it sounds like your config-section handler is not defined
<configSection>

</configSection>

Comment: How much of that type section is required?
Comment: You do not require Culture and PublicKey to solve your problem. Check my short version below.
Comment: @Daok: I was just following orders! ;-)
Answer: I had this identical issue recently. I created a custom sectiongroup for a web application(ran just fine), but when I ported this layer to a console app, the sectiongroup was failing.
You were correct in your question regarding how much of the "type" is required in your section definition. I've modified your configuration section with an example below:
<configSection>

</configSection>

You'll notice, the type now has class name followed by assembly name. This is required for interaction outside of a web environment.
NOTE: Assembly name does not necessarily equal your namespace(for a given section).
Answer: If you want a custom config handler you have to define the class and reference it as shown by Steven Lowe.  You can inherit from predefined handlers,  or you can just use the value/key pair that is offered in appSetting section as you noted.
Answer: At the top of your file you require to have configSection tag with inside the section.
You can have sectionGroup too. Example:
<configuration>
   <configSections>
     <sectionGroup name="x">

     </sectionGroup>
    <configSections>
</configuration>

Answer: This class works as a general custom configuration section handler for any type...
public class XmlConfigurator : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            if (section == null) return null;
            Type sectionType = Type.GetType((string)(section.CreateNavigator()).Evaluate("string(@configType)"));
            XmlSerializer xs = new XmlSerializer(sectionType);
            return xs.Deserialize(new XmlNodeReader(section));
        }
    }

In your app.config, add

And in the configuration section element, add an attribute to specify the type you want the root element deserialized into..
<?xml version="1.0" encoding="utf-8" ?>

<NameofConfigSection configType="NameSpace.NameofTypeToDeserializeInto, Namespace.Assembly" >

 ...

</NameofConfigSection>

Comment: But, as far as I can see, you can't duplicate the functionality that the code above provides (that is, being able to deserialize ANY configuration secrion with the same 'universal' handler) using the newer methodology...   Using ConfigurationSection, you have to write a new and diffe5rent derived class for each new configuration section you want to deserialize...
Comment: IConfigurationSectionHandler is deprecated in .NET 2.0 and above. Inherit from ConfigurationSection instead.

App.config - custom section not working


Why does this powershell command using Get-Service not continue if it encounters an error?

Question: I've been tasked with auditing Windows servers to see what services and programs are installed. I though PowerShell would be ideal for this, though I am new to PowerShell scripting.
I have a list of servers in a txt file and have been using the following commands.
Get-CimInstance -ComputerName (Get-Content .\servers.txt) -ClassName win32_product | Select-Object PSComputerName, Name, PackageName, InstallDate, IdentifyingNumber | Export-CSV -Path .\programs.csv
Get-Service -ComputerName (Get-Content .\servers.txt) -ErrorAction Continue | Select-Object MachineName, Name, DisplayName, Status, StartType | Export-CSV .\services.csv
The .\servers.txt is a simple text file with the server FQDNs.
If the server is inaccessible or not found, the first statement prints an error message and continues. As I understand the ErrorAction by default is to continue. However, the second statement fails and stops executing. I expect there will be errors and I could deal with them on a case by case, but why does the statement not continue on error as expected?
If I remove the bad server from the list, Get-Services runs fine. I'd rather get an error in the script and deal with that separately.
Update to include Powershell output
Get-Service : Cannot open Service Control Manager on computer 'computer_name'. This operation might require other privileges.
At .\get-service.ps1:1 char:1
+ Get-Service -ComputerName (Get-Content .\servers.txt) -ErrorAction Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
Comment: What is your $ErrorActionPreference  variable set to? "Continue"?
Comment: @LukasRäpple, yes, $ErrorActionPreference is Continue and I'm also being explicit about that in the Get-Services command.
Comment: I think what could be a problem is if the first command parses a wrong server, because of the continue statement the stdout will still be passed to Select-Object. But Select-Object is not able to access those Elements so it throws an error. You could try adding -ErrorAction to the second and third command as well. Also try removing this explicit -ErrorAction "Continue" completely one time.
Comment: @LukasRäpple Unfortunately I get the same error when adding the -ErrorAction parameter or if it is removed entirely.
Comment: Did you try a `try{}catch{}` statement? The error message also mentions privileges, do you have the required privileges for this operation?
Comment: @Alex_P the try/catch just ends the running of the script. My problem is the Get-CimInstance command works, albeit with errors printed, but Get-Service does not even for servers which are accessible. I need to complete this task for multiple domains and multiple servers and would find it easier to handle errors on a case by case, rather than the entire process failing :(
Answer: Just to show you how I imagined using a try-catch-statement.
$serverList = Get-Content .\servers.txt
foreach ($server in $serverLists)
{
  try
  {
    Get-CimInstance -ComputerName $server -ClassName win32_product | Select-Object PSComputerName, Name, PackageName, InstallDate, IdentifyingNumber | Export-CSV -Path .\programs.csv -Append
    Get-Service -ComputerName $server | Select-Object MachineName, Name, DisplayName, Status, StartType | Export-CSV .\services.csv -Append
  }
  catch
  {
    "Error on server $server occurred." | Out-File -FilePath .\errors.log -Append
  }
}

You could tweak the catch blocks to distinguish between CimInstance and the Service or instead of the generic error message you can forward the $_.Exception.Message.
Comment: Thanks @Alex_P. This is useful but it doesn't help me understand why the one cmdlet fails but the other works as I had written them before. Had I tested them the other way around, maybe I'd assume I'd coded it wrong in the first instance and never realised it would work. Alas, I'll revert to this method. Perhaps there is a bug in Get-Service?
Comment: @sbmobile, I would not assume a bug in `Get-Service`. Do you know which service throws the error? Is it always the same service on the same server?


Set global variable inside debounce function

Question: How to change the global variable inside called debounce function.  What does it mean - Can someone explain the "debounce" function in Javascript
function debounce(func, wait) {
  var timeout;
  return function () {
    var content = this, args = arguments;
    var later = function() {
      timeout = null;
      func.apply(content, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

var MANIPULATEDWPAGE = false;
function manipulatedwpage() {
  if (!MANIPULATEDWPAGE) {

     //MY CODE
     MANIPULATEDWPAGE = true; //only ones during debounce process

  }
}
window.addEventListener('resize', manipulatedwpage());
window.addEventListener('scroll', manipulatedwpage());

function calldeb() {

    //code after debounce done
    MANIPULATEDWPAGE = false;
    // <--- PROBLEM --- MANIPULATEDWPAGE is not changed

}
var debvar = debounce(calldeb, 2000);
window.addEventListener('resize', debvar);
window.addEventListener('scroll', debvar);

Comment: There's no global variable in the debounce function.
Comment: The second argument to `addEventListener` shouldn't have `()` after it. You want to pass a function reference so that the function will be called when the event happpens, not call the function immediately.
Comment: MANIPULATEDWPAGE means global variable because is outside function
Comment: I thought you were asking about a global variable that's actually in the `debounce()` function, not a variable that's used by the function that's being debounced.
Comment: I don't know how change "global" variable MANIPULATEDWPAGE in function calldeb()
Comment: You're doing it correctly already. Just assign the variable, there's nothing more to it. If you can't see the change, something else must be changing it back to `true`.
Comment: Solved, mistake was in listener, yes problem with addEventListener and (), thanks for help.
Answer: Here's the operations your code is running, reduced to just operations without control flow statements:
var MANIPULATEDWPAGE = false; // initial declaration
MANIPULATEDWPAGE = true; // run from function manipulatedwpage()
MANIPULATEDWPAGE = false; // run from debvar

You have two handlers on both the resize and scroll events. One of them sets your global to true, and then the other one comes along and immediately sets it back to false, making it look like it hasn't changed from its original state.
Comment: OK, just manipwpage() without () in resize and scroll listener, solved, unnecessary mistake elsewhere, sorry and thanks for help.


Windows Update state on fresh installations?

Question: I can't find this tiny bit of info anywhere: is Windows Update enabled or disabled by default on fresh installs of the OS? Basically I want to know whether it's on or does one have to manually enable it, even if it's the simplest user action.
If this varies from version to version (i.e. enabled by default on XP, disabled on Windows 7), I'd love to know about those differences as well.
Answer: It asks you on install on what state you would like it to set, to my knowledge its been the same between XP/Vista/7.
If you're question is about OEM machines with Windows pre-installed, I'd imagine that updates are enabled by default to 'Download updates and then inform the User that they're ready to install'
Comment: So, in effect, nothing will be installed until user performs an action granting permission to install; at least on OEM machines.
Comment: thats how it works on all our machines where I work, default is to download critial updates and wait until the user commits to install them. Of course there is always the option for them to be automatically installed
Comment: +1, but OEM pre-installs should still ask the user; that's part of the "out of box experience" which you get the first time you start the machine after installation.


Função iloc[] em Python (Pandas)

Question: Vi um código que a função iloc estava assim:
x = dados.iloc[0:-1, d:]
y = dados.iloc[d].values[0]

Li que iloc Seleciona a linha e coluna, mas o que seria aquele d ali ?
Answer: Adaptdado da documentação:
DataFrame.iloc
Indexação puramente baseada em localização através de inteiros para seleção por posição.
iloc[] é basicamente baseado em posções representadas por inteiros (de 0 ao tamanhyo-1 do eixo) mas também pode ser usado com um array booleano.
Entradas permitidas:

Um inteiro, por exemplo 5
Uma lista ou array de inteiros, ex. [4, 3, 0]
Um um objeto do tipo slice de inteiros, ex. 1:7
Um array booleano

Uma função que pode ser chamada com um argumento (Series, DataFrame ou Panel) e retorna uma saída válida para indexação (uma das opções acima). Isso é útil em cadeias de métodos, quando vc não tem uma referencia ao objeto de chamada, mas gostaria de basear sua seleção em algum valor. .iloc levantará a exceção IndexError se o índice requisitado estiver fora dos limites, embora a chmada via slices (de acordo com a semantica pyhton/numpy) admitam valores fora do limite.
Exemplos:
>>> mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},
...           {'a': 100, 'b': 200, 'c': 300, 'd': 400},
...           {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
>>> df = pd.DataFrame(mydict)
>>> df
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

Acessando a primeira linha do df com iloc[0]:
>>> df.iloc[0]
a    1
b    2
c    3
d    4
Name: 0, dtype: int64

# Investigando o tipo de objeto retornado qdo fazemos a chamada acima:
>>> type(df.iloc[0])
<class 'pandas.core.series.Series'>

Note que a chamada com iloc[escalar] não retorna um Dataframe e sim um objeto do tipo pandas.series.
Agora vamos acessar as duas primeiras linhas através de uma lista de inteiros:
>>>> df.iloc[[0, 1]]
     a    b    c    d
0    1    2    3    4
1  100  200  300  400

# Investigando o tipo de objeto retornado pela chamada acima:
>>> type(df.iloc[[0, 1]])
pandas.core.frame.DataFrame

Veja que agora tipo de objeto do retorno foi um pandas.DataFrame, algo como um "subdataframe".
Acessando com slices:
# Extrapoloando o limite
>>> df.iloc[:60]
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

# Começando em 2, indo até o final
>>> df.iloc[2::]
      a     b     c     d
2  1000  2000  3000  4000

Através de uma função, util em cadeia de metodos, no exemplo abaixo o indice é passado para lambda que retorna, ao fim, uma lista de inteiros pares.
>>> df.iloc[lambda x: x.index % 2 == 0]
      a     b     c     d
0     1     2     3     4
2  1000  2000  3000  4000

Note que o retorno foi um df com as linhas cujos indices eram pares no df original.
indexando os 2 eixos:
Podemos, também, fazer um mix entre índices e colunas, no exemplo abaixo vamos acessar o valor da segunda coluna da primeira linha e depois os valores da primeira linha e terceira coluna mais a segunda linha e quarta coluna
# Acessando o valor da primeira linha nas segunda coluna
>>> df.iloc[0, 1]
2

# Acessando os valores presentes na primeira e segunda linha na terceira e quarta coluna, respectivamente.
df.iloc[[0, 2], [1, 3]]
      b     d
0     2     4
2  2000  4000

Respondendo específicamente ao código na pergunta:
Para elucidar o código colocado na pergunta, vamos definir um valor para a variável d, provavelmente esse codigo foi tirado de um contexto em que essa variável estava definida.
x = dados.iloc[0:-1, d:]:
# Vamos copiar o valor de `df` definido acima para um novo df chamado `dados
>>> dados = df.copy()

# Vamos definir a variável d com o valor 2
d = 2

# Executando o primeiro comando do codigo da pergunga
x = dados.iloc[0:-1, d:]

# Apresentando o resultado
print(x)
     c    d
0    3    4
1  300  400

O resultado é a terceira e a quarta colunas (c e d) das linhas 0 e 1, note que o comando faz o que foi definido no tópico Indexando os 2 eixos com a utilização de slices, na semantica python/numpy, dados.iloc[0:-1, d:] indica um slice iniciando no índice 0 (linha 0) até a penúltimo ídicce (-1). As colunas foram selecionadas em função do valor da variável d (=2), ou seja da coluna 2 até a ultima (da c à d).
y = dados.iloc[d].values[0]:
Essa linha atribui à variável y o primeiro valor da terceira linha (visto que o valor da variável d é 2) do dataframe, ou seja, 1000:
# Relembrando os valores no dataframe
>>> print(dados)
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

# Lista dos valores na linha do índice equivalente à variável `d`:
>>> dados.iloc[d].values
array([1000, 2000, 3000, 4000])

# Executando segunda linha de codigo da pergunta
>>> y = dados.iloc[d].values[0]

# Apresentando o resultado:
print(y)
1000

Answer: Não cheguei a usar pandas, então não cheguei a usar este método, pelo que li, o iloc, é um método de seleção de dados, e de acordo com esse site, sua estrutura funciona da seguinte forma:
data.iloc[<row selection>, <column selection>]

Então neste caso creio eu que está recuperando os valores da primeira linha até a última, na coluna d em diante.
dados.iloc[0:-1, d:]  # a opção 0 é a primeira linha, é o -1 é a última, é o d: a partir da coluna d.

Claro não uso ciência de dados com python, mas pelo que ué li, creio que seja isso. Mas se alguém sabe é não for isso que disse posta aqui.

Função iloc[] em Python (Pandas)


iptables - synproxy target don't mark packets as INVALID

Question: I am writing iptables rulles and have problem with preventing flood SYN. Found that synproxy should be the right solution. But when testing, I found that it don't mark packets as INVALID, so iptables rule wont drop it.
$iptables -t raw    -A PREROUTING -p tcp -m tcp -m multiport --dports 25,80,443,587 --syn -j  CT --notrack
$iptables -t filter -A INPUT      -p tcp -m tcp -m multiport --dports 25,80,443,587 -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460
$iptables -t filter -A INPUT -m conntrack --ctstate INVALID -j LOG --log-prefix "IPTABLES=INVALID "
$iptables -t filter -A INPUT -m conntrack --ctstate INVALID -j DROP
$iptables -A INPUT -j LOG --log-prefix "IPTABLES=PASS "

As I understand it correctly, synproxy target should set invalid state to all packets that does not created 3 way hanshake, but when i use hping3 -c 10000 -d 120 -S -w 64 -p 80 --flood --rand-source 192.168.0.50 packets are logged as PASS not INVALID.
I also addded to sysctl more strict conntracking, this is necessary to have ACK packets (from 3WHS) marked as INVALID state.
/etc/sysctl.conf
net.netfilter.nf_conntrack_tcp_loose = 0
net.ipv4.tcp_timestamps = 1

I was using this blog post to understand whats happen. But there is nothing more i can change.
Could someone point me what I'm doing wrong?
iptables -nvL
Chain PREROUTING (policy ACCEPT 69965 packets, 9252K bytes)
 pkts bytes target     prot opt in     out     source               destination
38184 6109K CT         tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0 tcp dpt:80 flags:0x17/0x02 NOTRACK

Chain INPUT (policy DROP 98 packets, 4346 bytes)
 pkts bytes target     prot opt in     out     source               destination
34063 5450K SYNPROXY   tcp  --  !lo    *       0.0.0.0/0            0.0.0.0/0            tcp multiport dports 25,80,150,443,587 ctstate INVALID,UNTRACKED SYNPROXY sack-perm t imestamp wscale 7 mss 1460
    0     0 LOG        all  --  !lo    *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID LOG flags 0 level 4 prefix "IPTABLES=INVALID1 "
    0     0 DROP       all  --  !lo    *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID

Answer: Looks like SYNPROXY is working alright, it does not mark packets as INVALID but drops them immediately at SYNPROXY target. That's why i couldn't see INVALID packets.
Weird because previously hping disabled my OS and I had to reboot it, but now is everything alright. Maybe because i had no permanent sysctl settings turned on, who knows.


Receive URL by NSService, Drop on App-Icon or NSView: how to determine if it's already in sandbox?

Question: The App Sandbox Design Guide suggests saving all Security Scoped Bookmarks into NSUserDefaults.
When the user drops for example his home directory onto our app, we'll save that SSB. After a while, the user may drop something inside his home directory on to the app. How do I find out if I have to store this NSURL again as SSB?
Answer: Maintain a cache as pairs of absolute path (remove any symlinks), security scoped bookmark.
When adding a new item if it is a child on any of the existing ones its not needed. Otherwise add it and if its the parent of one or more remove them.


Where to find team stats/comparisons for Eurobasket 2015?

Question: The Eurobasket 2015 homepage is a disaster IMHO, although I can find simple information about players, I can't sort players by physical attributes or age etc.
Are there any pages which follow up the championship that have better roster pages? Alternatively is it possible to find the entire list of players (with stats) in raw text which I can play around with in R?
Comment: @posdef While I agree that this is on topic (per the discussion Ed and I had over at that question), his note is not unreasonable.  "Find this stat for me" is off topic (as this isn't an appropriate site for research requests), and this kind of question ("Where can I find stats on this") was never really discussed on its own.  That's why he linked to the discussion (and asked a question in comments).
Comment: Source request? See our [help center](http://sports.stackexchange.com/help/on-topic). Also, [related meta discussion](http://meta.sports.stackexchange.com/questions/583/sports-statistics-and-topicality?cb=1)
Comment: @edmastermind29 i dont see how asking for information regarding specific sporting events would be off-topic here on Sports.SE
Comment: Thanks, @Joe. posdef, you helped write our help center verbiage and in that verbiage, requests for sources/research have been explicitly stated as off-topic for some time. Given Joe's recent discussion on meta, we're looking for to how to deal with this fine line. re: the [meta discussion](http://meta.sports.stackexchange.com/questions/216/closing-of-my-question-about-finding-a-video-of-a-sporting-event) responsible for the verbiage wrt requests for sources/research, which is ironically wrt a specific sporting event.
Comment: @edmastermind29 interesting meta discussion, I have put my two cents on  the matter under that question.
Answer: EuroBasket is a fairly comprehensive site which covers all basketball in Europe, including Eurobasket 2015.
Comment: Can you show what pages would answer the request of the original poster - ie, pages with the rosters that include physical attributes or ages?  I can't find such on that page, for example, with a bit of checking...
Comment: All of the information is available.  However, for some details you need to be logged in to the site.
Comment: In fact I see rather better information on Eurobasket2015.org, presumably the page the original poster is talking about?
Answer: This Eurobasket page gives good top level information, and allows you to view stats by team if you go here. However, there are no sortable stats freely available on the site.
On the FIBA archive, there are sortable player stats, however, they do not include information like heights and weights. Same for this site.
That's all I have found. You can pay to get historic stats from the Eurobasket site initially linked, but that doesn't answer the question.
Note: There is github code for downloading live stats to analyze in R, but unfortunately not historic ones.
Answer: I think that this link can help you a lot and you can find here the Fiba Europe Stats Suite
Comment: Same as my comment on the other answer: I don't see how either of those provide the information requested by the original poster.  Please link to a specific example page that shows players with their physical attributes in a sortable or scrapable fashion.


Undefined reference to `MQTTClient_create' When I use CMake to cross compile the client

Question: I have cross-compiled the paho.mqtt.c to the so file and copy them to my lib directory in the workspace. I use the nm and readelf to check it, nothing goes wrong. But I can't use make to compile the sample client.c
$ readelf -h libpaho-mqtt3c.so
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              DYN (Shared object file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0x2a50
  Start of program headers:          52 (bytes into file)
  Start of section headers:          168104 (bytes into file)
  Flags:                             0x5000202, Version5 EABI, soft-float ABI, <unknown>
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         4
  Size of section headers:           40 (bytes)
  Number of section headers:         31
  Section header string table index: 28

$ nm libpaho-mqtt3c.so
00004c44 t MQTTClient_cleanSession
00004acc t MQTTClient_closeSession
000061d0 T MQTTClient_connect
00006234 T MQTTClient_connect5
000062e4 t MQTTClient_connectAll
000058c0 t MQTTClient_connectURI
0000503c t MQTTClient_connectURIVersion
000033b4 T MQTTClient_create
00002db8 T MQTTClient_createWithOptions
000086a0 t MQTTClient_cycle
00003aac t MQTTClient_deliverMessage
00003608 T MQTTClient_destroy
00006be8 T MQTTClient_disconnect

$ make
 [ 50%] Linking C executable ../bin/pub
    arm-openwrt-linux-uclibcgnueabi-gcc: warning: environment variable 'STAGING_DIR' not defined
    arm-openwrt-linux-uclibcgnueabi-gcc: warning: environment variable 'STAGING_DIR' not defined
    CMakeFiles/pub.dir/src/pub.c.o: In function `main':
    pub.c:(.text+0x78): undefined reference to `MQTTClient_create'
    pub.c:(.text+0x9c): undefined reference to `MQTTClient_connect'
    pub.c:(.text+0x100): undefined reference to `MQTTClient_publishMessage'
    pub.c:(.text+0x140): undefined reference to `MQTTClient_waitForCompletion'
    pub.c:(.text+0x168): undefined reference to `MQTTClient_disconnect'
    pub.c:(.text+0x174): undefined reference to `MQTTClient_destroy'
    collect2: error: ld returned 1 exit status
    make[2]: *** [CMakeFiles/pub.dir/build.make:85: ../bin/pub] Error 1
    make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/pub.dir/all] Error 2
    make: *** [Makefile:84: all] Error 2

here's my CMakeLists
cmake_minimum_required(VERSION 3.16)

project(CPE LANGUAGES C)

set(CMAKE_SYSTEM_NAME Linux)

set(CMAKE_C_COMPILER ${PROJECT_SOURCE_DIR}/toolchain/bin/arm-openwrt-linux-uclibcgnueabi-gcc)

set(CMAKE_CXX_COMPILER ${PROJECT_SOURCE_DIR}/toolchain/bin/arm-openwrt-linux-uclibcgnueabi-g++)

set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)

include_directories(${PROJECT_SOURCE_DIR}/include)

# aux_source_directory(./src SRC_LIST)
set(SRC_LIST ${PROJECT_SOURCE_DIR}/src/pub.c)

find_library(LIB ${PROJECT_SOURCE_DIR}/lib)

add_executable(pub ${SRC_LIST})

target_link_libraries(pub ${LIB})

Comment: `find_library(LIB` finds a library named `LIB`, like `libLIB.so`. I think you meant to find pago-mqtt3a or something like that.
Answer: - find_library(LIB ${PROJECT_SOURCE_DIR}/lib)
+ find_library(LIB paho-mqtt3c ${PROJECT_SOURCE_DIR}/lib)

Comment: If this is supposed to be an answer then it needs some context adding to make it actually useful.


Question regarding Solution to Geometric Probability

Question: I came across the following problem, while browsing my textbook, which was previously answered on this site.
Probability about a geometric distribution
I've attempted to solve the problem with the same reasoning, but with Bayes Rule, and have arrived at the same solution. However, I have trouble conceptualizing what the author meant in saying "If no-one obtains "head", the game continues with the same probabilities as before." If that is the case, why does that affect the probability recursively? Could someone explain why we add the case where no one wins to the probability, and why we multiply it by $p$?
Credit to joriki for the original solution, since the post is over a year old, I didn't want to ask a followup.
Answer: The game has three states:
$S$:$\quad\ $ So far nobody has thrown heads,
$M$: $\quad$Mary has thrown heads,
$M'$: $\quad\geq1$ of the boys has thrown heads, but Mary hasn't.
$M$ and $M'$ are terminal states with assigned probabilities $1$ and $0$ that Mary wins the game. Let $p$ denote the probability that Mary wins when we are in state $S$. The transition probabilities between the three states are as follows:
$$\eqalign{S\to M:\quad &p_2\cr
S\to M':\quad &(1-p_2)(p_1+p_3-p_1p_3)\cr
S\to S:\quad&(1-p_1)(1-p_2)(1-p_3)\cr}$$

Looking at the flow-chart we see that $p$ satisfies the equation
$$p=p_2\cdot 1+ (1-p_1)(1-p_2)(1-p_3)\cdot p\ ,$$
as given in Joriki's answer.
Comment: But I suppose my question should be, why have transition probabilities if the probability of each event is independent?
Comment: @zhuyxn: The independence of the three throws at each transition is built into the transition probabilities. The independence of the throws in subsequent transitions is reflected in the fact that only the resulting state is remembered.


why it is true that $F[\sqrt{a}] = F[\sqrt{b}]$?

Question: Suppose $\operatorname{char}(F) \neq 2.$ Suppose $a,b \in F$ are not squares, and let $E = F(\sqrt{a},\sqrt{b}).$ why if we assume that $[E : F] = 2,$ why it is true that $F[\sqrt{a}] = F[\sqrt{b}]?$
Any clarification will be greatly appreciated!
Comment: by Tower Law they are both field extensions of $F$ with degree 2. So $E=F[\sqrt{a}]=F[\sqrt{b}]$.
Comment: It is an application of a general theorem of linear algebra: for any $k$-dimensional vector space over a field $F$, any $k$-dimensional subspace is equal to the whole space.
Answer: It's because they're both ($F(\sqrt{a}), F(\sqrt{b})$) equal to the field $E$.
You have for example $2=[E:F]=[E:F(\sqrt{a})][F(\sqrt{a}):F]$ and since $[F(\sqrt{a}):F]$ must be $2$, the term $[E:F(\sqrt{a})]$ must be $1$ giving you $F(\sqrt{a})=E$.


In-line CTE in SQL

Question: Until today I thought that the CTE had to go before the main SELECT clause, but it appears that a CTE can be dropped into any subselect. As an example:
-- tested on BigQuery, Redshift, MySQL, Postgres
SELECT CONCAT(Odd.num, Even.num) FROM
  (WITH Numbers AS (SELECT 1 AS num UNION ALL SELECT 3 UNION ALL SELECT 5) SELECT * FROM Numbers) Odd,
  (WITH Numbers AS (SELECT 2 AS num UNION ALL SELECT 4 UNION ALL SELECT 6) SELECT * FROM Numbers) Even

Outside of just playing around with things though, is there ever a case for this sort of "embedded" CTE, or is there no reason to ever have it outside of the top, as if it's a variable declaration?
Comment: WITH is common query clause equal in rights to any other clause. Do not consider it like something special and exclusive. The query with CTEs can be used in any place (subquery or CTE) where the query w/o CTE can be used. And the only restriction is maximal nesting level.
Comment: I didn't even know this syntax were possible, before reading your question.  AFAIK, this syntax would never be necessary while running on the database itself.  But maybe you would need it when going through e.g. a JDBC driver.
Answer: Not only that, you can have CTEs inside of CTEs.
WITH CTE1 AS (
  WITH CTE2 AS (
    …
  )
)
SELECT …

I had to work on someone's query that did this 13 levels deep.  What a pain.  The main reason this isn't good is that it makes a mess of readability.  I think what you are describing isn't quite as bad as it keeps subsections of the query together.  Doing oddball things like this generally leads to confusion when others try to understand your query.
Comment: @samuelbrody1249 No, this is clear theory. In practice I have seen nested CTEs never.
Comment: wow, why did someone keep nesting CTEs? Were they trying to do something they couldn't do otherwise?
Comment: Well that was a conversation we had (as you can imagine).  This was written by a software developer with limited SQL / data engineering experience.  Their explanation was that they could turn on the functionality from the inside out.  So basically they replaced nested sub-selects with nested CTEs.   This was years ago when Redshift interpreted CTEs as optimization walls so this made a completely unoptimizable query.
Comment: *why did someone keep nesting CTEs? Were they trying to do something they couldn't do otherwise?* In solid WITH clause the names of separate CTEs must be unique. Nested CTEs allows the names interference freely - each used name is accessible only in the query where it is defined and in its nested subquery/CTE, and it masks the same name from the upper nesting level (including source tables/views). In practice this can be useful when the query is built dynamically.
Comment: @Akina I see, thanks. Are you able to share any practical examples you can think of or links to some code that shows that?

In-line CTE in SQL


Time series anomalies

Question: Suppose I have some time series. I already removed seasonality, so it consists of trend, some events and error.
I need to find the events, their length in periods,and their strength they had on the trend.
My idea is to divide data into several "windows", and calculate the length and strength
Do you know of a similar technique?
Answer: Ivan,
No.  I will point you to the work of Tsay www.unc.edu/~jbhill/tsay.pdf
You might not have removed the seasonality properly.  Did you look for seasonal pulses?
As for your outliers, there are outliers, there are level shifts, there are changes in trend as well as seasonal pulses.  You need to run a tournament of models with different approaches where you might need to look for the outliers first and then seasonality.   There could also be changes in parameters and variance that need to be tested for. Consider many many options.....post one data set here and perhaps we can do a deep dive?
Comment: http://onlinelibrary.wiley.com/doi/10.1002/for.3980070102/abstract  Introductory Economics > Journal of Forecasting > Vol 7 Issue 1 >
Outliers, level shifts, and variance changes in time series
Comment: The link is dead. I searched for Tsay and he published several books and papers. Which work was actually referenced here?

Time series anomalies


parentheses around a formula result

Question: How do I display the results of a formula -- e.g. "=(a1/b1)" which might return "45%" -- so that the result is surrounded by parens and appears as "(45%)"?  Putting parens around the formula -- e.g. "(=(a1/b1))" -- doesn't work.
Comment: Which environment are you talking about? Excel? Please tag your question accordingly.
Comment: If it is Excel, then use a custom format for your cell.
Answer: Do you mean in Excel? you can just set the format of the cell. how it should show the result.
Just right click on the Cell then format cells and then chose percentage on the left hand side. then change it to custome and put some parentheses arround the result. thats it ;)
Answer: Depends on the language you're using.
If =(a1/b1) works to give you "45%" then I would trying this: "(" + =(a1/b1) + ")"
Answer: I know this is an old thread but I thought it might be of interest for others as well.
To clarify the answer since it did not work for me when I tried it. In order to put the result from a function/formula within two parentheses in the same cell you need to use this function:
="("&(Cellfunction)&")".

In your case that would look like this:
="("&(A1/B1)&")".

If you have the same problem as the one asking the question, try copy/paste this funtion into a blank cell in a new sheet in Excel and type 1 into cell A1 and 2 into cell B1.
When using the funcion in the blank cell (for example C1) the result should be 0,5. This function also works for displaying parentheses around a returned answer. For example: Cell D252 displays the result from Cell C7 (C7 could have its own function/formula). That's how I used the function which looked like this:
="("&(C7)&")"

Hope this helps,
Best,
Felix, Business administration student in Sweden
I'm using Mac and Excel for Mac Home and Student 2011.
Answer: The easiest way to do this is to format the cells. Choose Custom on the left side. Then in the empty field type in:
(0)
This will put your value in parentheses. If you want the value to be carried to 1 decimal place then type in:
(0.0)
etc.

parentheses around a formula result


How to use jEditable module with Computed Field module?

Question: I've done some computations using Computed Field module like the follows.
First
Second
Total(first+second) (computed field)
I've installed jEditable inline content editing module to do inline edit at node display. How to use this module with computed filed. Here is my problem
Lets say I've node like the following
First - 35
Second - 4
Total  - 39
If I change the value of First from 35 to 38 (using jEditable field) and save, it's updating the filed, but the value of total remains the same. I'm getting correct result when I refresh the page. (Ofcourse, I know the reason).  I need to get updated value of total whenever I change the values of first/second. How can I achieve this?
For better understand I've added images
Answer: The jEditable, is based on an ajax request, and it works only for your first field, it's normal what you see there untill you refresh page to see changes...
here some snippets that can help :
1- create a callback menu item :
function MYMODULE_menu(){
$items['edit_total/ajax'] = array(
    'title' => t('Edit Total AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'edit_total_ajax',
    'access arguments' => array('access content'),
  );
return $items;
}

2- create the callback function that will return the new total field :
function edit_total_ajax(){
    $data = array();

    if(isset($_POST['first']) && isset($_POST['second'])){
        $first = $_POST['first'];
        $second = $_POST['second'];
        data['total'] = (is_numeric($first) && is_numeric($second)) ? $first + $second : "undefined";
    }
    drupal_json_output($data); // return data as json output, this is the best return for me!
}

3- Now you must have a simple jQuery snippet to send the first and the second value :
$(function(){
  // you can add here an event handler (on submit for examle)
  jQuery.ajax({
       type: "POST",
       url: '/edit_total/ajax', // the same that made in hook_menu
       dataType: 'json',
       data: { first: $("YOUR_FIRST_SELECTOR").val(), second: $("YOUR_SECOND_SELECTOR").val()  },
       success: function(data){

                 if(data.total !== 'undefined'){
                        $("YOUR_TOTAL_SELECTOR").text(data.total) // this is will change the text value of total field by the new one !
                    }
                 }
       });
});


Semidirect product, normal subgroup exercise

Question: Let $G$ be a group and let $H,K$ be subgroups of $G$ such that $G=H \rtimes K$.
(i) Show that if $K \lhd G$, then $kh=hk$ for all $h \in H, k \in K$.
(ii) Deduce that $G$ is abelian if and only if $H,K$ are abelian and $K \lhd G$
I am completely lost with the exercise. First of all, the hypothesis is that $G$ is isomorphic to the external semidirect product of $H$ and $K$, but it doesn't say anything about the morphism $\rho:K \to Aut(H)$, I know that the external semidirect product multiplication is $(h_1,k_1).(h_2,k_2)=(h_1\rho(k_1)(h_2),k_1k_2)$. I don't know how to use the fact that $K$ is normal and the structure of the semidirect product in order to show (a) or (b), I would appreciate hints and suggestions to do both parts of the problem.
Comment: @user16924. Well, if $G$ is *equal* to an internal semi-direct product, then it is *isomorphic to* the corresponding external semi-direct product (for some choice of the action $\rho$).
Comment: @user16924: Have a look at Dummit and Foote's algebra book.
Comment: @voldemort Thanks, I'll think about the other implication and write it down.
Comment: Note that the hypothesis is that the group $G$ is *equal* to the internal semi-direct product of $H$ and $K$. It is not necessary, for this problem, to introduce an explicit action of $K$ on $H$; it is implicit in the group operation in $G$, and that is enough.
Comment: The hypothesis is not that $G$ is isomorphic to the external semidirect product, but rather that it is the internal semidirect product of those.
Comment: @tomasz Are you sure that $G=H \rtimes K$ doesn't mean it is isomorphic to the external? Because $H \rtimes K$ is the notation for the external semidirect product, not the internal. Sorry if I am saying something wrong but I am just learning these concepts.
Comment: The same question for @James
Comment: Sorry if this is not the place to ask, but could you recommend me a textbook that deals with semidirect and direct products?
Comment: @user16924: If it was as you say, then it would be like $G\cong H\rtimes K$, which it isn't. There is no special notation to distinguish internal semidirect products that I'm aware of.
Answer: Let $K \lhd G$. Then, $h^{-1}(k^{-1}hk)$ lies in $H$ as $H$ is normal, and $(h^{-1}k^{-1}h)k$ lies in $K$ as $K$ is normal. As their intersection is $1$, we have that $h^{-1}k^{-1}hk=1$, i.e. $hk=kh$.
Now, If $H$, $K$ are abelian, and $K \lhd G$, then the above computation shows that all elements of $G$ commute, and so $G$ is abelian.
The converse is trivial (why?)
Note that we do not require the actual automorphism $\rho$ for any of the above computations.
Comment: @user16924: Every $x \in G$ can be written as $hk$ for some $h \in H$ and $k \in K$. So, $xy=h_1k_1h_2k_2$. Now, $k_1h_2=h_2k_1$ as $K$ is normal (from above computation). So, $xy=h_1h_2k_1k_2$. Also, $yx=h_2k_2h_1k_1=h_2h_1k_2k_1$. Since $H$ is abelian, $h_1h_2=h_2h_1$. Since $K$ is abelian, $k_2k_1=k_1k_2$. Thus $G$ is abelian.
Comment: The converse is trivial because if $G$ is abelian and $h,h' \in H$, then $hh'=h'h$, since $h,h'$ are also in $G$, the same goes for $G$. Now, let $g \in G$, take an element $gkg^{-1}$ from $gKg^{-1}$, then $gkg^{-1}=(gg^{-1})k=ek=k \in K$, so $gKg^{-1}=K$, from here it follows $K$ is normal.
Comment: Sorry to bother again but I don't quite see why from $(i)$ one deduces that $H,K$ abelian and $K$ normal implies $G$ abelian. Take $x,y \in G$, then $xy=hk$, I want to show that $xy=yx$ or, equivalently $xyx^{-1}y^{-1}=e$, I don't know how to finish from there.
Answer: Hint: For (i), show that the commutator $[h,k] = h^{-1}k^{-1}hk\in H\cap K$, for $h\in H$ and $k\in K$.  You need that $H$ and $K$ are both normal for this.


Como linkar paginas Word Press Criação de Temas

Question: Estou começando a criar temas com wordpress, e não sei como fazer com que as paginas que eu crio no painel apareceram no meu tema através do menu, o menu eu consegui adicionar através de funções no functions.php e no header.php, mas as paginas que eu adicionei no menu através do painel não aparecem quando eu clico nelas pelo menu, acho que é porque não configurei a pages.php ou algo assim, não sei bem, comecei agora e não sei como o wordpress funciona se alguém poder me dar uma luz eu agradeço ;)
Answer: No wordpress você deve criar um arquivo pages.php como página padrão, esse arquivo vai ser usado para renderizar todas as páginas que você criar no admin do wordpress. Se você precisar de um template exclusivo para alguma página é necessário adicionar um comentário template name no início do seu arquivo. Com esse comentário você consegue selecionar o modelo de página no admin.
<?php

 /**
  * Template name: Página de Contato
  */

 // Arquivo que vai renderizar a página de contato.


Reordering values in a multi value field

Question: Is there a module that allows you to reorder the values of a multi value field?  By drag and drop or by weight.
Example:
Field XYZ:
+ Value 1
+ Value 2
+ Value 3
+ Value 4

Reorder to:
Field XYZ:
+ Value 4
+ Value 2
+ Value 3
+ Value 1

Comment: You think fields as in fieldable entities? O form api elements?
Answer: If you need to do this in the context of adding/editing nodes, Drupal 7 core provides this functionality on node add/edit pages.
Answer: You can Try Multiple value widget module.

Drupal utilizes draggable tables to handle multiple value forms. It's
  quite convenient for most simple field types. However, for complex
  field types such form can be cumbersome. For example, the widget for
  Image field type can contain a preview of a file, an upload button, a
  text field for title and alt attributes. Sometimes you have a lot of
  images to be uploaded and the form takes up a lot of space.

This module integrates the jQuery UI tabs and accordion plugins as a replacement for draggable tables to make multiple value forms more user friendly. All field items can still be ordered through jQuery UI sortable widget.


Leaflet Map disappears when selecting term in views exposed filter

Question: I'm using leaflet in a content view with a page having an exposed filter on taxonomy terms.
Problem is whenever a term/filter is selected and applied the map disappears and turns grey.
I'm using Leaflet More Maps and this seems to happens with any map.
Comment: is term/filter having data? if not please select show map when there is no data.
Comment: Yes there is data. There are nodes created with the selected terms... The map disappears and shows as a blank grey box.
Answer: You must use global area views from other block with generic map, should not have results always show you the map.


call an Oracle function that do an insert/update from PHP?

Question: we have a function if we call it by using SELECT we get the error code ORA-14551 "Cannot preform a DML operation inside a query"
select pkg_tools.replace_site(1121,3343) from dual;

how to run this function and get the results
when we run it in SQL developer in this way:
declare
v_return VRACHAR2(200);
begin
v_return := pkg_tools.replace_site(1121,3343);
end;

works with no errors
and we need this function to be called inside PHP
note: I can not paste this function here, because it's to long, but it does allot of operations including insert and update!
Comment: How are you connecting to Oracle from PHP? (oci8?).  Just refer to those docs on calling a stored procedure in Oracle.  Quick Googling gave me: http://www.oracle.com/technetwork/articles/fuecks-sps-095636.html
Comment: yes we have it, and it works with simple queries
Answer: A function that does DML cannot be called in a SELECT statement regardless of the calling language.
If you want to do DML and return a value, it would make much more sense to create a stored procedure with an OUT parameter rather than using a function.  So it would make much more sense to
CREATE OR REPLACE PROCEDURE proc_name_return( p_1    IN NUMBER,
                                              p_2    IN NUMBER,
                                              p_ret OUT VARCHAR2 )
AS
BEGIN
  p_ret := pkg_tools.replace.site( p_1, p_2 );
END;

and then call that stored procedure from PHP
$sql = 'BEGIN proc_name_return( :p_1, :p_2, :p_ret ); END;';

If you don't want to do that, my guess is that you could do something like this as well (adapted from one of the scripts on page 164 of the Underground PHP and Oracle Manual)
<?php
$c = oci_connect('hr', 'hrpwd', 'localhost/XE');
$s = oci_parse($c, "begin :ret :=pkg_tools.replace_site(1121,3343); end;");
oci_bind_by_name($s, ':ret', $r, 200);
oci_execute($s);
echo "Result is: ".$r;
?>


Prove that sets being equipotent is an equivalence relation

Question: Let $X$ and $Y$ two subsets of $E$. We know that $X$ and $Y$ are equipotent, $X\sim Y$, if there exists a bijective function so that $f:X\rightarrow Y$. Proof that $\sim$ defines an equivalence relation in $\mathcal{P}(E)$.
I don't know how to do that, please help me!
Comment: Have you tried showing if the defining properties of an equivalence relation hold for the given relation?
Comment: That's the problem, I don't know how to define the relation
Answer: To see reflexivity, observe that the identity map on $X$ is a bijection. To see symmetry, observe that bijections have inverses, so if $X\sim Y$, then there is a bijection $f:X\to Y$, so there is a bijection $f^{-1}:Y\to X$. To see transitivity, observe that the composition of two bijections is a bijection, so if $X\sim Y$ and $Y\sim Z$, then there are bijections $f:X\to Y$ and $g:Y\to Z$, so you have a bijection $g\circ f:X\to Z$ which implies $X\sim Z$.
Comment: Great, thank you Stan!


What are all possible actions by automorphism of $H = \Bbb Z/3\Bbb Z$ on $N = \Bbb Z/6\Bbb Z$?

Question: So the question is "What are all possible actions by automorphism of H on N?" with H = Z/3Z and N = Z/6Z.
I completely guessed my way through how to go about solving this, but I started with finding Aut(Z/6Z) which is {[1],[5]}, and figured that it Aut(Z/6Z) must be isomorphic to Z/2Z.  Working through I found that the only possible action is the direct action Z6 x Z/3Z.
This is most likely wrong, and any help will be greatly appreciated.
Comment: Wait..."*automorphisms* of [group] on [a non-isomorphic group]"? I suspect that you may be using the term [automorphism](http://en.wikipedia.org/wiki/Automorphism) in a non-standard way. Please clarify.
Comment: Maybe he means a homomorphism from $H\to Aut(N)$, as for a semidirect product?
Comment: Sorry!  I meant to say "actions by automorphism"
Answer: As you've computed, the group of automorphisms of $\mathbb{Z}/6\mathbb{Z}$ is of order $2$. An action of $\mathbb{Z}/3\mathbb{Z}$ on $\mathbb{Z}/6\mathbb{Z}$ thus arises from a homomorphism from a group of order 3 into a group of order 2, and any such homomorphism is trivial. Thus there is only the trivial action.
Comment: My answer is correct?  Awesome! Thank you so much.
Comment: @JamesNorton You're welcome.


Add margin between row elements bootstrap

Question: I have 3 different elements in my row class with bootstrap. I wish to create a margin (of 20px for example) between EACH of the elements in the row container. Since the elements are divided into 4 equal spaces of the row container (on the same line), adding a margin class with a margin parameter of 20px pushes the other elements to the next line (whereas I want to keep them all in the same line).
My current code

About Us

Contacts

Upcoming Events

Comment: How about adding a `padding` to `.col-sm-4`, and set .col-sm-4 to `box-sizing: border-box;`. See this example: https://jsfiddle.net/pe0w20kd/ Is this what you want?
Comment: If I had a padding and the box-sizing to the margin, I can see that the containers are still side by side (I've added a border around the elements which is how I can see).
Answer: Created a fiddle to make things clear .
https://fiddle.jshell.net/q1je1kct/
Is this you wanted
Added
display:inline-block;
Update

https://fiddle.jshell.net/q1je1kct/4/

If you don't want the elements jumping to newline , take a look into this
https://fiddle.jshell.net/q1je1kct/5/

Created using flex concept.

new Update as suggested
https://fiddle.jshell.net/q1je1kct/8/
Comment: Thanks for your answer. However, with your latest update, even I hover over the elements, I can still see that they are side by side (in terms of clicking on the links). I'd like to have a gap between the elements, as in if I hover over the space in between, it wouldn't show me the hand link (i.e the way the cursor changes to a hand when you hover over a link). So even though visually there is a gap, the elements are still not spaced out.
Comment: I've tried your code and it works the way I've wanted it to with just a few modifications. I've accepted the other answer simply because it seems a "cleaner" way to represent the code. Thank you for your help.
Answer: I've changed the structure to a more proper one I think. And I use padding on h4 element.
See this fiddle

                About Us

                About Us

                About Us

Comment: Thanks for the answer. This is indeed what I want. I've tweaked it a little bit as well to include a border around each element block.
Comment: You're welcome. I think it's better to not overload bootstrap classes by adding fixes on it and preferable to change elements in it :)
Comment: I agree. Best to keep the code nice, clean and simple!


Timeline database schema?

Question: I'm having trouble finding a good database structure/schema for a timeline.
I have a site where a user can create many types of objects, these objects have many different properties and so are saved in many different tables.
My timeline does display all the different objects ordered by date.
My idea was to insert a record in my timeline table when a new object is created:
insert into timeline (date, objectType, objectId) values (...)

To display my timeline i do:
select * from timeline order by date desc limit 100

No problem here. Next i need to get the object data that will be displayed on my timeline, simply:
select * from objectType where id = objectId

for every single entry in my timeline. And this will becomes the problem, these are way to many queries.
Of course i can fine tune it with:
select * from objectType where id in (objectId, objectId)

But still when there are many objectTypes in my timeline it still are a lot of queries.
Anyone got a bright idea on a better approach?
Comment: what's wrong with `IN`? You can do it in one query. but depending on your application structure, you might have to do deferred execution or rendering.
Comment: @KarolyHorvath with IN you will have 1 query for every objectType, if there are for example 10 objectTypes with each their own table you will have 10 queries for every objectType + the timeline one.
Answer: You don't say which flavour of SQL you're using, so it's hard to say what kind of syntax to answer with.  Here is some pseudo-code to give you an idea:
Create a temporary table (or view) that connects the displayable details of different types using UNION and then select the TOP/LIMIT from that.
You can join the timeline to your various object types, projecting each object type's properties into a consistent displayable format based on converting the native columns in each object type:
CREATE VIEW displayable_events
AS
select
  e.date, e.objectType, e.objectID,
  o.ColumnOfInterest1 + '-' + o.ColumnOfInterest2 as Description
                      -- Or whatever you want to show
from timeline e
  inner join objectTypeA o
    on e.objectID = o.objectID
where e.objectType = 'TypeA' -- or whatever you're using to distinguish them.
--
UNION ALL
--
select
  e.date, e.objectType, e.objectID,
  o.ColumnOfInterest1 + 'anything else you like' as Description
from timeline e
  inner join objectTypeB o
    on e.objectID = o.objectID
where e.objectType = 'TypeB'
--
UNION ALL
--
... and so forth for all of your object types...

Then you can select from this view (or temporary table) like so:
SELECT * from displayable_events
WHERE -- whatever you use to distinguish whose timeline you want ---
ORDER BY date DESC
LIMIT 100

This saves you doing all of the queries individually for each timeline entry because it uses a set-based approach.
Comment: Thanks for your thoughts on the subject, i'm going to dive a bit into views cause i never really worked with them.

Timeline database schema?


Why are tokens added to image URLs?

Question: When I'm use the image_style_url(), function I got this token at the end of the URL: ?itok=yjoxJwQh.
Drupal uses a different token for styles and script, eg ?mk4o7m.
How does this affect caching and SEO?
Comment: I had answered the [similar question](http://drupal.stackexchange.com/a/63232/6461) sometime ago. As mentioned by MPD, it is done by the Drupal Security team to avoid denial of service attack.
Answer: This was a change that was introduced in Drupal 7.20, which addressed a denial of service vulnerability:

Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.

From the release notes:

The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

Drupal 7.21 revised this a little:

Drupal 7.20 fixed a fundamental security flaw in the Drupal core Image module and therefore introduced incompatibilities with a number of contributed modules and sites (see the Drupal 7.20 release notes). To help mitigate the effect of these changes, an optional image_allow_insecure_derivatives variable was provided, which sites could use to turn off the security fix.
Drupal 7.21 adds additional security protection for sites that use this variable. Although they will still not receive the full benefit of the security fix, they will now have protection against the most damaging and easiest-to-inflict vulnerabilities that were addressed in Drupal 7.20.
Comment: This explains the why of the image token, but not that of the other tokens mentioned, nor does it actually answer the question: how does this affect SEO and caching?
Answer: Since version 7.20, Drupal adds a security token to the URL of derived images (that is, images that are manipulated by an image style, e.g. to get a thumbnail or an otherwise cropped version of a base image). The token is created when the appropriate HTML to render an image with a given image style is generated and usually shouldn't change after it has been created. The reason for this is that without it, anyone could request derived versions for any image they knew existed on a site (which is not hard to find by examining img tags in use on the site) for any image style they knew existed on a site (which is also not that hard to find with the same method). Since the derived image is created when it is first requested, this would put a high load on the system, creating a denial of service. With the token, it is first checked before starting generation of the derived image. This means derived images will only be created for base image and image style combinations that were intentionally output in the site's HTML.
Since version 7.21, this behaviour can be disabled using a hidden configuration variable (i.e. it would need to be set in the settings file, or through a tool like drush), image_allow_insecure_derivatives.
See the release notes of these Drupal versions 7.20 and 7.21 for more details.
"Tokens" on JS files and CSS files are simply "cache busters", i.e. intended to force clients to re-download the resource, usually because it has changed.
Image tokens should have minimal impact on caching, because they usually remain the same from the first moment the html for the derived image is generated (possibly, the tokens are wiped too when the image styles are flushed, but that shouldn't happen under normal circumstances). "Tokens" on other resources are, as said, intended to affect caching; they are designed to force redownloading of the resource (but only when that is needed).
Effect on SEO should, I think, also be minimal, although I am less qualified to comment on that. AFAIK, search engines are pretty good at knowing whether a GET variable should be considered part of the URL (i.e. it determines the actual content of the resource) or just something technical. Even if they don't consider that, I think JS and CSS URLs shouldn't really have any impact on SEO anyway. With images, it shouldn't really matter whether the token is considered to be part of the URL or not, since it shouldn't really change, normally (and then still, the only place where I think it might be actually relevant is in image search results).

Why are tokens added to image URLs?


Trouble understanding solution for trig problem

Question: I have a problem that I am supposed to solve that is as:
Solve the trig equation $2\cos\theta + \sqrt{3} = 0$
Eventually it gets to $\cos^{-1}(\frac{\sqrt{3}}{2}) = \frac{\pi}{6}$
What I would like to know is how pi over 6 was arrived at. I imagine my teacher will want me to represent everything as algebraically as possible, so I think it's important to understand.
Here is a screenshot of the full problem:
Comment: Start with an equilateral triangle of side $2$, draw a line from a vertex to a midpoint of a side. Your $\pi/6$ and its cosine come from there.
Comment: I don't understand what you mean. What is an equilateral triangle of side 2?
Comment: It is an equilateral triangle all of whose sides have length $2$.
Comment: Okay, I still don't understand. I suppose I am not familiar with that principle.
Comment: I assume you know we are working in radians, so $\pi/6$ is what in degrees is called $30^\circ$. Draw an equilateral triangle of side $2$.  Call it $ABC$. Draw a line from $A$ to the midpoint $M$ of $BC$. Look at triangle $AMC$, which is right-angled at $M$. Note that by the Pythagorean Theorem we have $AM=\sqrt{3}$. So the cosine of the $30^\circ$ angle $MAC$ is $\sqrt{3}/2$.
Comment: Okay, this all makes sense to me now except why we are assuming $AM=\sqrt{3}$ . Why is it that according to Pythagorean Theorem that is so?
Comment: The hypotenus $AC$ is equal to $2$, and $MC$ is equal to $1$, since it is half of $BC$. Thus $AM^2=AC^2-MC^2=4-1=3$.
Answer: If you know that $$\cos\left(\dfrac\pi6\right)=\dfrac{\sqrt{3}}2,$$ then it follows that $$\cos^{-1}\left(\dfrac{\sqrt{3}}2\right)=\dfrac\pi6.$$
Comment: Ah, so maybe I should be referencing some sort of chart of values? I guess this is just simply understood?
Comment: @byteofthat Or just do exactly as I did.


Can you loop over a comma separated list of values in a mysql stored procedure

Question: I need to loop over a comma separated list of IDS that were passed into a stored procedure.  I have seen people use locate() and substring  etc but I haven't seen anything that really makes sense.
Thanks!
Comment: What are you doing that requires pulling the values out of a comma separated list?  Have you googled for a split function?
Comment: looks like I could pass in the length of the comma separated list and use SELECT ELT  to loop over the list.  From what I have read, mysql / relational databases in general are not very good at calculating an occurence of a string, so I think it  would be better to pass in the count, still researching though.
Answer: Maybe this is something like you want? http://forge.mysql.com/tools/tool.php?id=4
Basically it is used to convert a comma delimited string into a table.
Comment: the provide link is now broken


C# datagridview shound not change until there is a result

Question: Recently i developed a search function, but i want when a user inputs something on the textbox the datagridview to not go blank but instead to show the data that it already has and when the result is found than only show the result. Because now when i type anything on the search textbox the dgv immediately goes blank.
Here is my code:
<code> private void txtBarkod_TextChanged(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(txtBarkod.Text)) {

            resetTxTboxes();

        }
        MySqlConnection connection = Connection.prevzemiKonekcija();
        try {

            connection.Open();
            MySqlCommand command;
            MySqlDataAdapter adapter;
            DataTable tabela;

            string query = "SELECT * FROM artikli WHERE barcode  like '%" + txtBarkod.Text + "%'";
            command = new MySqlCommand(query, connection);
            adapter = new MySqlDataAdapter(command);
            tabela = new DataTable();
            adapter.Fill(tabela);
            dataGridView1.DataSource = tabela;

            if (txtBarkod.Text == "") {

                ShowDgV();

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {

            connection.Close();

        }

    }
</code>
Answer: Reset/Rebind the datasource of your datagridview only if you found something in your db.
<code>if(tabela.Rows.Count > 0)
{
    dataGridView1.DataSource = tabela;
}
</code>


Mysql Auditing for Security

Question: Is there a Auditing tool for mysql?
When i googled i can see some triggeres and procedure which can say who is logged and how times and those informations are provided.
For DML we are able to store the before image of the table and that to it is for specific table.
I m looking for a auditing tool which can audit the security of the databases.
Answer: You can't audit throug a tool...(you can but isn't right)
A tool for security auditing is IBM Consul InSight but.. the price si too big. You can read some standards or some books and you can audit your security based on standards.. A tool isn't capable to analyse a problem from all points of view. A human person can, especially +two
For security auditing docs, you can visit isaca and for begin, you can read oreily presentation and after that... isaca article
I hope that my post can help you, and if you have more questions..go ahead.

Mysql Auditing for Security


Live Search using only PHP, JS

Question: We just got homework to do live search, but we can't use AJAX or jQuery but neither we can use button to send a form. So is there any solution for this?
Comment: but as the post title says JS . you still have option to search it with javascript. instead of jQuery and ajax
Answer: Call the function when the user types the key
Use JavaScript's
onkeyup="function()"
On the textbox that is taking the input and
later in the function perform the required search(use php or js whatever is needed)
Comment: Oh, I forgot that onkeyup even exists. Yep that solved this problem, thanks! I guess I could search more about javascript.
Comment: As you are new, i would like to suggest you something. Whatever answer helped you solve the problem you should mark it as accepted.
Comment: Ok, sorry I will remember that.
Comment: Don't use smart quotes, that will break the code. Also, inline handlers are as bad as `eval` - separate presentation from content, much better to attach handlers in Javascript instead.

Live Search using only PHP, JS


Why `search.web` YQL table doesn't work anymore?

Question: When I'm using search.web YQL table, I always get the error:

No definition found for Table search.web

in my YQL statements. Even when using SELECT url FROM search.web(0,10) WHERE query="stackoverflow" for example.
So I am assuming Yahoo discontinued search.web or BOSS? What are the alternatives? Is there still a similar way to crawl the web?
Answer: We can read in YQL Blog:

We've removed all search tables that relied on the BOSS v1 API (search.web, search.image, and search.news) as the aforementioned BOSS v1 no longer exists as of today (http://www.ysearchblog.com/2011/06/30/you-asked-for-this-boss-v2-updates/).
For those of you relying on those tables please consider using the community BOSS v2 table (https://github.com/yql/yql-tables/blob/master/boss/boss.search.xml).
Thanks -YQL Team

Source: Search tables and BOSS v1 in YQL Blog.

As a result, you should move to another search service like Y! BOSS v2. As mentioned above there are already open data tables for that, and an example query would look like:
SELECT * FROM boss.search WHERE query="stackoverflow"
AND ck="your oauth consumer key"
AND secret="your oauth secret"

Another alternative is to use Bing search:
SELECT * FROM microsoft.bing.web WHERE query="stackoverflow"

Answer: BOSS v1 API has been depreciated (as in YQL Blog), so you should use BOSS v2 API which works exactly the same, but the table is called boss.search and it's available in Yahoo YQL Dev Console (just activate Show Community Tables or check at GitHub).
To use BOSS v2 API, you need to have your own Consumer Key and Consumer Secret which can be generated at Yahoo Dev Apps by creating a new app.
Sample usage:
select * from boss.search where q = "sam pullara" AND (ck = 'ConsumerKey') AND (secret = 'SECRET');


Jquery $.get wont run on $(document).ready

Question: im running a project in MVC and wanted to call a action on the page load, however it dosnt seem to be working.
<code>$(document).ready(function () {
   $.get('@Url.Action("Test", "Home")', function (HtmlData) {
     alert(HtmlData);
  });
});
</code>
All my other Jquery code runs just fine, and if i take the .get and put in a button press it works just fine.
Any ideas?
Comment: `however it dosnt seem to be working` How that? No alert shown or what? Error in console?
Comment: If you want page load means `window.onload = function() { // your code}`
Comment: can you verify if ANY code runs in your ready function?  If you placed an `alert` above the `$.get` would that fire?
Comment: Have you checked F12 Developer tools for any errors?
Comment: Works on mine. There's something else wrong in the page/script. F12 and check the console for errors
Comment: All code outsite of the $.get runs fine, if i place an alert before or after it runs just fine, the alert inside of it however does not run.
EDIT: The console gives no errors.
Answer: After deleting the code, rebuilding the project and re-writing the code the code now runs just fine. Sorry for any inconvenience.