if condition: (64 > 360) is true?

Question: I have a bit of code in Javascript, which returns true when it obviously shouldn't. For context: I have a mindmap and in order to find the most extreme coordinates of the map, I cycle through all nodes and check if this node has a higher/lower value than the currently highest/lowest value. When running the code the method returns wrong values and with console.log() I think I found something weird, but don't know how to fix it.
findMaxX(maxX){
        console.log("this.x before test:"+this.x);
        console.log("maxX before test:"+maxX);
    if (this.x > maxX){
        console.log("this.x:"+this.x);
        console.log("maxX before:"+maxX);
        maxX = this.x;
        console.log("maxX after:"+maxX);
    }
    this.children.forEach(element => {
        maxX = element.findMaxX(maxX);
    })
    return maxX;
}

What I find in the console is this:
maxX before test:360
this.x before test:288
maxX before test:360
this.x before test:64
maxX before test:360
this.x:64
maxX before:360
maxX after:64
this.x before test:65
maxX before test:64

It seems to be working just fine, but at some point the condition seems to return true for an obviously false statement. Is there some noob mistake I'm doing? Where can I search for errors? My code looks fine to me and I can't see a connection to the observed error. I'm happy for all hints! Thank you
Comment: I would guess this is a type issue, if your values are stings your `>` will not give the same result as for numbers.
Comment: Maybe `this.x` or `maxX` can be `string`. If so the condition may not work as expected
Comment: Just use === operator when compare.
Comment: It would help if you shared example values and how you get them
Comment: yes you were all right, I thought javascript recognizes numbers on its own, but it seems like it doesn't. I now use Number() to make sure the saved coordinates are numbers, thanks to everybody!!
Answer: It seems to me that this.x and maxX could be strings. And that's why you obtain these results. Here you can see these examples (run this code snippet):

let xNumber = 64, yNumber = 360;
let xString = "64", yString = "360";

console.log(xNumber > yNumber);
console.log(xString > yString);

And read some information about the comparison of different types in JavaScript here
Also, as a suggestion to obtain what you need (if you want to compare these variables as numbers), I would advise converting them to Number, for example in this way:

if (parseFloat(this.x) > parseFloat(maxX)) {
  // here your code
}
Comment: use parseFloat here since you said that you're working with coordinates

if condition: (64 > 360) is true?


Como ler uma planilha do Excel 2013 e gravar em um banco de dados PostgreSQL?

Question: Estou com problemas em gravar informações no banco de dados.
Essas informações eu extraio de um arquivo do Excel.
Por exemplo, tenho 3 campos e não sei como pegar a 1ª célula e gravar no banco, depois pegar a 2ª e gravar e por fim pegar a 3ª e gravar.
Lembrando que são várias informações que cada coluna possui.
Meu código está assim:
public void readingSheet(String path) {

    try {

       File file = new File(path);

       String name = file.toString();

       int pos = name.lastIndexOf('.');

       String ext = name.substring(pos + 1);

       FileInputStream fileIn = new FileInputStream(file);

       Workbook obj = null;

       if (ext.equals("xlsx")) {

           try {
               //Metodo aceita o path do arquivo
               obj = new XSSFWorkbook(fileIn);
           }

           catch (IOException ex) {
               throw new RuntimeException(ex);
           }
       }

       else if (ext.equals("xls")) {

           try {
               //Metodo nao aceita string do path do arquivo
               obj = new HSSFWorkbook(fileIn);
           }
           catch (IOException e) {
               throw new RuntimeException(e);
           }
       }

       else {
           throw new IllegalArgumentException("Arquivo recebido não é uma extensão do Excel");
       }

       int o = 0;

       Sheet worksheet = obj.getSheet("Plan1");

       Row row;

       Cell cell;

       for(int i = 1; i<= worksheet.getLastRowNum(); i++){

           row = worksheet.getRow(i);

           String linha = "";

           for(int j = 0; j < 3; j++) {
               cell = row.getCell(j);

               if(cell.getCellType()==1)   {
                   linha += " | " + cell.getStringCellValue();
               }

               else {
                   double aux = 0;
                   int aux2 = 0;
                   aux = cell.getNumericCellValue();
                   aux2 = (int) aux;
                   linha += " | " + aux2;
              }
          }
           System.out.println("");
           System.out.println("Linha: " + linha);
           System.out.println("");
       }

   }

    catch (FileNotFoundException e) {
      e.printStackTrace();
   }

}

Obrigado a todos.
Comment: Poderia colocar exemplos de valores das colunas? Dependendo do caso se possível, é mais simples converter a planilha em csv e importar esse arquivo direto pelo banco.
Comment: Claro, username "Fernando" - fullname "Fernando Santos" - password "teste"
Answer: Aconselho a usar a biblioteca jxl para manipular planilhas do excel. Só não testei com o excel 2013.
Aqui vai um exemplo de manipulação
O código de exemplo é esse
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;

public void readingSheet(String caminho_arquivo_xls) {
    //objeto relativo ao arquivo excel
    Workbook workbook = null;

    try {
        //Carrega planilha
        WorkbookSettings config = new WorkbookSettings();
        config.setEncoding("Cp1252");//configura acentuação
        workbook = Workbook.getWorkbook(new File(caminho_arquivo_xls),config);//recupera arquivo desejado
        //recupera pagina/planilha/aba do arquivo
        Sheet sheet = workbook.getSheet(0);
        //recupera numero de linhas
        int linhas = sheet.getRows();
        //percorre todas as linhas da planilha
        for (int row = 0; row < linhas; row++) {
            //cria meu objeto que recebe as linhas
            MeuObjeto objeto = new MeuObjeto();
            //verifica se coluna 0 (A) e linha row não é vazia
            if(!sheet.getCell(0,row).getContents().isEmpty()){
                //recupera informação da coluna A linha row.
                objeto.setDadoA(sheet.getCell(0, row).getContents().toString());
            }
            if(!sheet.getCell(1,row).getContents().isEmpty()){
                //recupera informação da coluna B linha row.
                objeto.setDadoB(sheet.getCell(1, row).getContents().toString());
            }
            //chama meu objeto que faz o serviço de salvar no banco de dados
            bancodados.salvarDado(objeto);
        }

    } catch (IOException e) {
        print_erro(e);
    } catch (BiffException e) {
        print_erro(e);
    } catch (NumberFormatException e) {
        print_erro(e);
    } catch(Exception e){
        print_erro(e);
    } finally {
        //fechar
        if (workbook != null)
            workbook.close();
    }
}


Não consigo juntar duas tabelas em php

Question: boa tarde, estou com o seguinte problema, estou a desenvolver um projeto e preciso de juntar duas tabelas do mysql para aparecerem na tabela feita em php. Ou seja, eu quero o seguinte:

esta tabela supra tem de receber informação da tabela utentes e de outra tabela. Já tentei de tudo mas a tabela aparece sempre vazia. Tenho o seguinte código

<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0)
    {
header('location:index.php');
}
else{
?>

<!DOCTYPE html>

        <title>CSSJD | Página Inicial</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <meta charset="UTF-8">
        <meta name="description" content="Responsive Admin Dashboard Template" />
        <meta name="keywords" content="admin,dashboard" />
        <meta name="author" content="Steelcoders" />

        <link type="text/css" rel="stylesheet" href="../assets/plugins/materialize/css/materialize.min.css"/>
        <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link href="../assets/plugins/metrojs/MetroJs.min.css" rel="stylesheet">
        <link href="../assets/plugins/weather-icons-master/css/weather-icons.min.css" rel="stylesheet">

        <link href="../assets/css/alpha.min.css" rel="stylesheet" type="text/css"/>
        <link href="../assets/css/custom.css" rel="stylesheet" type="text/css"/>

        <?php include('includes/header.php');?>

       <?php include('includes/sidebar.php');?>

                                Total Utentes
    <?php
$sql = "SELECT id from tblutentes";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$dptcount=$query->rowCount();
?>
                                <?php echo htmlentities($dptcount);?>

                                Total PIIs Preenchidos
                                    <?php
$sql = "SELECT id from  tblpii";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$leavtypcount=$query->rowCount();
?>
                                <?php echo htmlentities($leavtypcount);?>

                                    Últimos Utentes Preenchidos

                                            ID
                                            Nome Utente
                                            Número Utente

                                    <?php $sql = "SELECT tblpii.NomeUtente as nomeutente,tblutentes.* from tblutentes join tblpii on tblpii.id=tblutentes.id order by lid desc limit 3";
                                    $query = $dbh -> prepare($sql);
                                    $query->execute();
                                    $results=$query->fetchAll(PDO::FETCH_OBJ);
                                    $cnt=1;
                                    if($query->rowCount() > 0)
                                    {
                                    foreach($results as $result)
                                    {  ?>

                                            <?php echo $cnt;?>.
                                            <?php echo $row['nomeutente'];?>
                                            <?php echo $row['nrutente'];?>
                                            <a href="manageleavetype.php?manageleavetype=<?php echo htmlentities($result->lid);?>" class="waves-effect waves-light btn blue m-b-xs"  > Ver Detalhes

<?php }} ?>

Answer: Já tentou usar INNER JOIN ?
EX:
"SELECT * FROM c_endereco INNER JOIN c_cliente ON c_cliente.idunico_cliente = c_endereco.idunico_cliente INNER JOIN c_cadastro ON c_cadastro.idunico_cliente = c_endereco.idunico_cliente WHERE c_endereco.idunico_cliente='$clienteid';"

Você pode fazer com quantas tabelas quiser, se não entendeu muito bem de uma pesquisada sobre inner join tem muita tutorial!

Não consigo juntar duas tabelas em php


Using k-means with other metrics

Question: So I realize this has been asked before: e.g. What are the use cases related to cluster analysis of different distance metrics? but I've found the answers somewhat contradictory to what is suggested should be possible in the literature.
Recently I have read two papers that have mention using the kmeans algorithm with other metrics, for example edit distance between strings and the "Earth Mover Distance" between distributions. Given that these papers mention using kmeans with other metrics without specifying how, particularly when it comes to computing the mean of set of points, suggests to me that maybe there is some "standard" method to dealing with this that I'm just not picking up on.
Take for example this paper, which gives a faster implementation of the k-means algorithm. Quoting from paragraph 4 in the intro the author says his algorithm "can be used with any black box distance metric", and in the next paragraph he mentions edit distance as a specific example. His algorithm however still computes the mean of a set of points and doesn't mention how this might affect results with other metrics (I'm especially perplexed as to how mean would work with edit distance).
This other paper describes using k-means to cluster poker hands for a texas hold-em abstraction. If you jump to page 2 bottom of lefthand column the author's write "and then k-means is used to compute an abstraction with the desired number of clusters using the Earth Mover Distance between each pair of histograms as the distance metric".
I'm not really looking for someone to explain these papers to me, but am I missing some standard method for using k-means with other metrics? Standard averaging with the earth mover distance seems like it could work heuristically, but edit distance seems to not fit the mold at all. I appreciate any insight someone could give.
(edit): I went ahead and tried k-means on distribution histograms using the earth mover distance (similar to what is in the poker paper) and it seemed to have worked fine, the clusters it output looked pretty good for my use case. For averaging I just treated the histograms as vectors and averaged in the normal way. The one thing that I noticed is the sum over all points of the distances to the means did not always decrease in a monotone manner. In practice though, it would settle on a local min within 10 iterations despite monotone issues. I'm going to assume that this is what they did in the second paper, the only question that remains then is, how the heck would you average when using something like edit distance?
Comment: @ttnphns I disagree with (2). That is Lloyds algorithm, not generic k-means. K-means in general means minimizing the sum-of-squares-partitions objective. What you described is the generic expect-maximize (EM) pattern; and Lloyds is the EM pattern for least-squares models.
Comment: The 2nd link duplicates the 1st.
Comment: Scooby Thanks for interesting links. The first paper (which I've just looked through on the fly) describes a (supposedly) new clustering method/algorithm which is based on the idea of [triangle inequality](http://en.wikipedia.org/wiki/Triangle_inequality) of a metric. It is _not_ what people mean under the term k-Means method/algorithm. So the _title_ of the article is somewhat misleading, for me. The proposed "triangle inequality" clustering method, _when_ applied to Euclidean distance metric, should give results identical to what "K-means" method would give, as the author claims.
Comment: In its strict sense, K-means procedure implies (1) objects by (numeric) features input matrix; (2) iterative reassignment of objects to clusters by computing Euclidean distance between objects and cluster centres (which are cluster _means_). Everything above or istead of that - e.g. analyzing a matrix of pairwise distances or making use of other metric than Euclidean or computing other form of centre than the mean, etc. - extends or modifies K-means so it becomes not k-means in the original sense.
Answer: It's not as if k-means will necessarily blow up and fail if you use a different metric.
In many cases it will return some result. It is just not guaranteed that it finds the optimum centroids or partitions with other metrics, because the mean may not be suitable for minimizing distances.
Consider Earth movers distance. Given the three vectors
3 0 0 0 0
0 0 3 0 0
0 0 0 0 3

The arithmetic mean is
1 0 1 0 1

which has EMD distances 6, 4, 6 (total 16). If the algorithm had instead used
0 0 3 0 0

the EMD distances would have been 6, 0, 6; i.e. better (total 12).
The arithmetic mean does not minimize EMD, and the result of using k-means (with artihmetic mean) will not yield optimal representatives.
Similar things will hold for edit distances.
Comment: Choose the canonical such matrix, from the original motivation: moving earth, with cost=distance.
Comment: I'm not sure if I follow how you computed the EMD distances.  By my understanding you need a transition matrix with weights for moving from one feature to another.
Answer: K-means is appropriate to use in combination with the Euclidean distance because the main objective of k-means is to minimize the sum of within-cluster variances, and the within-cluster variance is calculated in exactly the same way as the sum of Euclidean distances between all points in the cluster to the cluster centroid. As other answers point out, the algorithm is only guaranteed to converge (even if to a local minimum) if both the centroid update step and the data points reassignment step are done in the same n-dimensional Euclidean space.
Also, it has been shown (and I put a link here because I myself cannot explain this) that the mean is the best estimator to be used when one needs to minimize total variance. So k-means tie to the Euclidean distance is two-fold: the algorithm must have some way to calculate the mean of a set of data points (hence the name k-means), but this mean only makes sense and guarantees convergence of the clustering process if the Euclidean distance is used to reassign data points to the nearest centroids.
You can still use k-means with other distance measures, as in this paper, in which the author uses the algorithm with the Minkowski distance, which is a generalization of the Manhattan, Euclidean and Chebyshev distances. However, in these cases, convergence is not guaranteed and, as a consequence, you might expect that future iterations of the algorithm will actually have greater total variance than previous iterations.
Even so, as shown in the paper above, even without the guarantee of convergence, k-means can achieve better clustering results in some scenarios by using other distance measures. If you take the $L^p$ norms, for example, and knowing that the Euclidean distance is the $L^2$ norm and that the Manhattan distance is the $L^1$ norm, it has been shown that, for sparse distance matrices, k-means used in conjunction with an $L^p$ norm with $0 < p \leq 1$ achieves greater clustering accuracy than when using the Euclidean distance.
Lastly, I think it is interesting to point out that there are some similarity measures that can in some way be converted to the Euclidean distance, in such a way that if you use said similarity measure in conjunction with k-means, you ought to get similar results. An example of that is the cosine similarity.
Comment: Lp for p < 1 is not a norm.
Answer: I don't know if this is what the linked papers are doing, but it is possible to do k-means with non-Euclidean distance functions using the kernel trick. That is, we implicitly map the inputs to a high-dimensional (often infinite-dimensional) space where Euclidean distances correspond to the distance function we want to use, and run the algorithm there. For Lloyd's k-means algorithm in particular, we can assign points to their clusters easily, but we represent the cluster centers implicitly and finding their representation in the input space would require finding a Fréchet mean. The following paper discusses the algorithm and relates it to spectral clustering:

I. Dhillon, Y. Guan, and B. Kulis. Kernel k-means, Spectral Clustering and Normalized Cuts. KDD 2005.

There are kernels based on the edit distance and based on the earth mover's distance.

Using k-means with other metrics


Strange manipulation with a dummy variable to solve a summation

Question: I get sometimes summations where I need to change a number by a dummy variable to integrate/differentiate the sum to get the closed form.
The method works but it seems too strange changing a parameter by a variable to manipulate something and after revert the change to get the solution. An example:
$$\sum_{k\ge 0}k3^k\binom{n}{k}\overset{\text{strange temporal manipulation}}{\longrightarrow}\sum_{k\ge 0}kx^k\binom{n}{k}$$
Then
$$\sum_{k\ge 0}kx^k\binom{n}{k}=x\sum_{k\ge 0}kx^{k-1}\binom{n}{k}=x\frac{\mathrm d}{\mathrm dx}\left(C+\sum_{k\ge 0}x^k\binom{n}{k}\right)=\\=x\frac{\mathrm d}{\mathrm dx}\left(C+(x+1)^n\right)=nx(x+1)^{n-1}$$
Now I change back to get the solution (what is correct)
$$\sum_{k\ge 0}k3^k\binom{n}{k}=3n4^{n-1}$$
Two questions:

We need something special to justify these manipulations?
There are better methods to solve these sums without the need of this manipulation? Im searching specifically, if exist, some alternative integrate/differentiate that dont need this kind of dummy variable method

Thank you in advance.
Answer: I find that something is wrong in your formulas. First, you are asking for the sum with 'k' being negative. I think you meant to be 'k' from zero to 'n'. Then you make a mistake taking out a 'k', which has no sense, because it is the variable that runs inside the summatory. You should have taken an x outside instead.
Finally you obtain $$nk4^{(n-1)}$$ but I think you should have $$3n4^{(n-1)}$$
Answering your questions:
1) The only thing you need to justify is that your substitution can be differentiated. As long as you have $$(x+1)^n$$ it is perfectly differentiable, so you can do this.
2) I think this procedure works pretty well. I don't know any better method. Usually you'll find these kind of summation when dealing with discrete probabilities. You can make a list of common summations to get it done faster, but I think the formal idea works just fine. For sure there should be more ways to get the same result, but let me doubt them to be more straightforward than this.
You have to be carefull with the variable k. It is different going from zero to n or from 1 to n... Depending the case you are, you will have to extract (or introduce) a term of the summation so you can write the resulting sum.
Comment: Yeah, a lot of typos, sry. Thanks!
Answer: Note that $k{n\choose k}=n{n-1\choose k-1}$. So $$\sum_{k\ge0}k3^k{n\choose k}=\sum_{k\ge0}n3^k{n-1\choose k-1}=3n\sum_{k\ge0}3^{k-1}{n-1\choose k-1}=3n4^{n-1}$$
Comment: Beautiful... I generally see the diferentiable form before that any other solution.


Problemas com arquivo web.xml

Question: <code>Warning: selected war files include a WEB-INF/web.xml which will be ignored
(webxml attribute is missing from war task, or ignoreWebxml attribute is specified as 'true')
</code>
Estou usando o Netbeans para trabalhar com um projeto Spring e ate o momento não tinha me deparado com esse aviso.
A IDE executava o projeto normalmente.
Embora use o pluggin do jetty para rodar pelo terminal , eu usava o tomcat do netbeans e a aplicação  rodava sem problemas..
Agora so roda pelo terminal com o pluggin do jetty..
Fiz umas mudanças no codigo e de repente comecei a ver essa mensagem, então  voltei varios commits quando o codigo ainda funcionava.
Para a minha surpresa a mensagem voltou a aprecer!! E não consigo rodar pela IDE netbeans
O que esta ocorrendo? E como resolver isso?
Answer: Como você usou o comtrole de versão e ate certo ponto de sua apicação tudo estava em funcionando perfeitamente.
Como alguma coisa aconteceu e essa mensagem começou  a aparecer e você voltou ao commit onde tudo funcionava bem,reconpilou e tentou implantar, mesmo assim a IDE mostra que existe um defeito, isso quer dizer que ela esta comrrompida.
Para reslver esse problema desisntale o netbeans complertamente.
"É raro" mas o netbeans corrompe seus dados de configuração  e fica mostrando essa mensagens obsoletas!

Problemas com arquivo web.xml


Name of matrix operation of [ A[0] dot B[0], A[1] dot B[1] ] from 2x2 matrices A, B

Question: Please advise how this matrix operation is called, and what is the numpy operation for it. np.inner, np.dot does not create dot products from 2x2 matrices.
Answer: This is the diagonal of the matrix product $AB$, which can be obtained in NumPy using numpy.diagonal and numpy.matmul.
For example
import numpy as np
A = np.matrix('0 1 2; 3 4 5')
B = np.matrix('0 -3; -1 -4; -2 -5');
np.diagonal(np.matmul(A,B)) # or (A*B).diagonal()

yields
array([ -5, -50])

However, this does compute the off-diagonal entries of the matrix product as well and hence isn't very efficient. Describing the entries of your resulting vector as
$$
v_i = \sum_j a_{ij} b_{ji}
$$
you can obtain the same result more efficiently using numpy.einsum as
np.einsum('ij,ji->i', A, B)


How do you use the Drupal 7 overlay on the node/edit screens for your popups when it's already being used?

Question: I'm writing a module that adds a button to node/edit forms. This button needs to popup a DIV/IFRAME in a light box. I notice that Drupal 7 uses the new Overlay module for administrative and node/edit pages.
So my question is as my button is on a node/edit page I need to overlay the overlay. Is there a way to access the overlay and change or z-index or do I just write my own overlay code to create a light box effect (overlaying the node/edit overlay)?
Answer: It is possible to change the z-index used by the overlay, but I don't think it's necessary. You just use for your overlay a z-index that is higher than the one used by the Overlay module.
In the case you need to know when the overlay is output, or how it is output, you should check the code executed by overlay_page_alter(), which is the implementation of hook_page_alter() made by overlay.module.
function overlay_page_alter(&$page) {
  // If we are limiting rendering to a subset of page regions, deny access to
  // all other regions so that they will not be processed.
  if ($regions_to_render = overlay_get_regions_to_render()) {
    $skipped_regions = array_diff(element_children($page), $regions_to_render);
    foreach ($skipped_regions as $skipped_region) {
      $page[$skipped_region]['#access'] = FALSE;
    }
  }

  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }
  elseif ($mode == 'parent' && ($message = overlay_disable_message())) {
    $page['page_top']['disable_overlay'] = $message;
  }
}


Qual é a finalidade do construtor de uma enum?

Question: Em Java construtores são necessários para criar um objeto na memória, ou seja, para instanciar a classe que foi definida. Entretanto, eu descobri que uma enum possui um construtor, porem ele não é uma classe, e eu pensava que apenas as classes possuíam construtores.
Veja esta enum como exemplo:
public enum Genero
{
    MASCULINO(1), FEMININO(2);
    public int codigo;

    private Genero(int codigo)
    {
        this.codigo = codigo;
    }
}

Nota:

Considere que a enum esta dentro de uma classe que representa uma
  pessoa, classe Pessoa.

Veja que para usar a enum a classe não precisa ser instanciada, exemplo:
Pessoa.Genero.FEMININO

Gostaria de saber qual é a finalidade do construtor de uma enum e se a enum tem as mesmas propriedades de uma classe?
Comment: Curiosidade: apesar de conceitualmente o Enum não ser mesmo uma classe (o construtor não pode ser público e não é você que cria instâncias dele, por exemplo), ele tem diversas características de uma classe regular, podendo ter atributos, comportamentos e inclusive membros estáticos. De fato, olhando o bytecode gerado (o código java compilado, por assim dizer), podemos notar que Enums geram o mesmo o código que uma classe depois de compilados.
Comment: Isso, o conceito é diferente: enquanto uma classe pode ter toda sorte de funções, **a função do Enum deveria ser estritamente a de representar uma lista fixa de valores constantes** (é claro que lista e valores podem mudar entre compilações - mas em tempo de execução ela é fixa). Dada a flexibilidade do Enum no Java, já vi programador implementando até regras de negócio complexas dentro do Enum - isso pode trazer algumas dificuldades conforme o sistema cresce. Minha resposta fica dispensada dada a excelente resposta já postada pelo @utluiz ;-)
Comment: @Caffé A sim, é o a mesma coisa que uma classe, porem muda o conceito certo. Você poderia publicar uma resposta explicando?
Answer: Construtores de enums em java são usados em situações onde você quer adicionar mais informações aos valores do enum além do seu nome. No seu exemplo, a sua enum tem associada aos valores MASCULINO e FEMININO os códigos 1 e 2 (*), respectivamente. A vantagem disso é que você pode continuar usando os nomes que fazem sentido (MASCULINO, FEMININO), mas quando for armazenar os valores (por exemplo, num banco de dados) você armazenaria o valor associado a eles (novamente, nesse caso, assumindo que o seu esquema do BD use 1 para homens e 2 para mulheres).
Outras vantagens de associar mais dados aos valores da enum é a possibilidade de você adicionar uma lógica na enum mesma. Um exemplo que eu já vi é de um SDK, onde cada valor da enum tem um código (string), e uma função extra na enum é usada para concatenar todos os valores a partir de um EnumSet.
(*) - Declarar o campo que armazena o valor agregado como public não é apropriado, pois um código mal-escrito pode alterá-lo e o seu programa pode começar a ter erros difíceis de serem identificados.
Comment: @DenerCarvalho Outra opção é declarar como *final*, assim: `public final int codigo;`, assim ele também não poderá ser modificado depois de ter seu valor atribuído no construtor do enum. Eu uso bastante o *final* nestas situações e em outras estruturas de dados para evitar a verborragia do "get".
Comment: Sim, privado, com um método get para acessá-lo, algo como `public int getCodigo() { return this.codigo; }`
Comment: O campo código deve ser private neste caso?
Answer: TL;DR
Construtores em Enums tem exatamente a mesma finalidade de construtores em classes, inicializar valores. Enums não são nada mais do que um tipo específico de classe.
Enums são classes
A primeira coisa para entender definitivamente Enums é que eles não são nada mais do que classes com algumas características específicas e "açúcar sintático".
Vejamos, a pergunta tem o seguinte exemplo de Enum:
public enum Genero
{
    MASCULINO(1), FEMININO(2);
    public int codigo;

    private Genero(int codigo)
    {
        this.codigo = codigo;
    }
}

Poderíamos facilmente reescrever o exemplo acima como uma classe normal:
public class EnumGenero {
    public static final EnumGenero MASCULINO = new EnumGenero(1), FEMININO = new EnumGenero(2);
    public int codigo;

    private EnumGenero(int codigo)
    {
        this.codigo = codigo;
    }
}

E o uso fica praticamente igual:
EnumGenero masculino1 = EnumGenero.MASCULINO;
Genero masculino2 = Genero.MASCULINO;

Pontos importantes:

Constantes de Enums não são nada mais do que atributos estáticos. Veja no exemplo como eu instancio a classe nas constantes. É a mesma coisa com o Enum, a diferença é que você não precisa colocar os modificadores de acesso nem o new, mas o comportamento é exatamente o mesmo.
Enums são instanciados exatamente como classes. Como disse no item anterior, a diferença é que o new fica implícito na sintaxe simplificada do Enum.
O construtor do Enum é sempre private e você não precisa colocar esse modificador, é redundante. No caso da classe, depende de você colocar ali para evitar que outras instâncias sejam criadas.

Enums vs. Classes
Existe alguma diferença entre usar Enums e classes como a que coloquei acima? Vamos considerar as diferenças para o exemplo cima.
Sobre o Enum:

Pode usar com switch e algumas IDEs avisam caso você esqueça de colocar algum valor.
Sintaxe simplificada que dá certas garantias, tais como que não haverá outras instâncias além das constantes pré-definidas.
Métodos auxiliares como name(), ordinal(), valueOf() e values().

Sobre a classe:

Mais flexibilidade, permite herança e outras construções, embora isso geralmente não seja recomendado a não ser que haja uma razão muito forte.
Desvantagem de você ter que adicionar manualmente todos os modificadores de acesso, além da instanciação de cada constante.
Não tem os métodos auxiliares do Enum por padrão, mas podem ser implementados, embora não de forma muito simples e segura.

Observações sobre a implementação do Enum
Encapsulamento
O seu Enum pode ter o atributo codigo acessado via getter:
public enum Genero {
    MASCULINO(1), FEMININO(2);
    private int codigo;

    private Genero(int codigo) {
        this.codigo = codigo;
    }
    public int getCodigo() {
        return codigo;
    }
}

Existe alguma necessidade disso? Tecnicamente não.
Embora geralmente seja desejável encapsular os atributos para não permitir o acesso direto via código externo, este argumento não é tão forte quando falamos de constantes.
O valor não muda e não há um motivo forte neste caso específico para encapsular um atributo que tem baixíssima probabilidade de mudar no futuro.
Entretanto, as razões mais fortes para usar um getter é para manter consistência (é ruim trabalhar num sistema onde ora os atributos são expostos, ora não são) e para possibilitar refatoração interna no futuro, mesmo que isso não seja visível agora.
Uma situação onde eu não recomenda usar encapsulamento é em classes internas onde o uso do valor é privado. Exemplo:
public class ProcessaAlgoComGenero {
    public enum Genero {
        MASCULINO(1), FEMININO(2);
        private int codigo;
        Genero(int codigo) {
            this.codigo = codigo;
        }
    }
    public void processaGenero(Genero g) {
        System.out.println(g.codigo);
    }
}

E a chamada fica assim:
new ProcessaAlgoComGenero().processaGenero(ProcessaAlgoComGenero.Genero.MASCULINO);

Perceba que o atributo codigo somente é acessível dentro da classe ProcessaAlgoComGenero. Encapsular um atributo usado apenas internamente é desnecessário.
Recuperando valores pelo código
É algo comum quando adicionamos atributos aos valores do Enum precisarmos recuperar as constantes com base nesse valor.
Enquanto para recuperar a constante com base no nome usando o método pronto valueOf(), temos que construir o outro método nós mesmos.
Então, se em algum momento você precisar recuperar o Enum pelo codigo, pode fazer isso:
public static Genero ofCode(int codigo) {
    for (Genero g : values()) {
        if (g.codigo == codigo) {
            return g;
        }
    }
    return null; //ou lança uma exceção
}

Note que o método ofCode percorre todos os valores do Enum através do array retornado por values() e procura pela constante com o codigo a ser recuperado.
A vantagem desse código ao invés de um if ou switch é que você pode reaproveitá-lo para qualquer situação, inclusive outros Enums, com um mínimo de alteração.
Você poderia fazer simplesmente assim:
public static Genero ofCode(int codigo) {
    if (MASCULINO.codigo == codigo) return MASCULINO;
    if (FEMININO.codigo == codigo) return FEMININO;
    return null; //ou lança uma exceção
}

Mas nesse caso para cada enum você teria que reescrever tudo.
Se houver muitas constantes e o tempo de execução for uma preocupação, você pode usar um mapa para tornar o tempo de procura constante.
Primeiro você precisaria inicializar o mapa logo que o Enum for inicializado. Basta adicionar isso no Enum:
static Map<Integer, Genero> cache = new HashMap<>();
static {
    for (Genero g : values()) {
        cache.put(g.codigo, g);
    }
}

E depois o método ofCode é trivial e eficiente:
public static Genero ofCode(int codigo) {
    return cache.get(codigo);
}

Considerações
Usar Enum é bom, facilita a codificação e faz com que o código fique mais seguro contra equívocos e mesmo contra programadores "espertinhos".
Enums são flexíveis como classes, embora com várias outras restrições. Como visto no exemplo acima, é possível criar construções complexas dentro de Enums. Porém, use isso somente em casos onde realmente for necessário, caos contrário você está adicionando complexidade e dores de cabeça desnecessárias ao seu programa.
Answer: Funciona de forma similar, mas você não pode chamar o construtor você mesmo.
No exemplo que você colocou, o construtor é chamado duas vezes e MASCULINO e FEMININO são inicializados com o valor passado (1 e 2 respectivamente).
A principal diferença desse enum para uma classe, é que no enum, todos os objetos declarados no início são iniciados automaticamente e mais nenhum depois disso.
Comment: Neste casso para usar a enum eu devo fazer isso: `Pessoa.Genero.FEMININO` a classe não é instanciada para utiliza-lo.
Comment: Na verdade, acho o exemplo ruim. Nesse caso seria melhor não usar o construtor, para poder acessar como você comentou.

Da forma como passou, usando construtor, o ideal é fazer um método para pegar os valores que quiser e só deveria usar se o enum for mais complexo que isso.
Comment: Sim, mais ainda não consigo entender a finalidade do construtor já que não é possível fazer `Pessoa.Genero genero = new Pessoa.Genero(2)`, o construtor seria realmente necessário na enum?
Comment: Seria útil se o enum fosse algo mais complexo. Se no lugar de Gênero, fosse um enum de personas. Você poderia ter definido no enum alguns atributos como Gênero, Idade, Profissão, etc.
Comment: Como assim mais complexo?
Comment: Mal, acabei editando enquanto você perguntava.


Expert Guidance on Body Posture when Playing Bansuri

Question: So far when I play Bansuri, my torso is twisted to the left, while sitting cross-legged on my bed (and I attempt to sit straight). And my head is slightly bent at an angle.
I see others playing Bansuri also sitting cross-legged (on the floor), but their torso is facing forward. And their head is slightly bent at an angle.
Initially when I try this alternate position, I get more air into my Bansuri, but I get tired sooner.
Please tell me if there is recommended guidance for body posture when playing Bansuri.
Somehow I am thinking my body posture is causing me to breathe less air into my Bansuri (plus I am beginner at less than a year practice)
Answer: Start with:
Posture for playing
Then investigate comparable sitting postures in Yoga that emphasize freeing pressure on the diaphragm. Using chest muscles for breathing will tire the player quickly. Use of the diaphragm in breathing is a technique used not only by many woodwind players, but also martial arts practitioners. Try sitting on the floor to give the lower back more support and consequently reinforce the diaphragm. A bed, while immediately more comfortable, will certainly not offer the base provided by the floor.
Of course, more practice will strengthen all of the muscles used in playing.
Please refer to tags on this forum for breathing, woodwinds, bansuri, flute, for many useful tips.
Comment: Wow this is a low to chew on! Will start by sitting on the floor!


Using Intern in conjunction with Selenium and dynamic proxyUrl

Question: my configuration is an intern test environment launched by grunt and the following intern config (partly):
proxyPort: 9000,
proxyUrl: 'http://<my-ip>:9000',

The problem is the hardcoded my-ip. Selenium grid and nodes are running on different machines / respective ips and the config file for intern is to be checked in together with all the build and test environment.
If I leave proxyUrl at localhost the selenium nodes can't load the data for the intern tests.
Thus my-ip will be different for all developers testing. I really don't want everybody to enter the own ip into the intern config and accidently check in config, neither to check in a template file for everybody to change.
Don't understand me wrong. The setup is working just fine but the local ip has to be entered hardcoded which I personally see as smell.
Maybe its easy to parametrize the proxyURL but I just can't find any resource for it :(
Regards,
Flowkap
Answer: As of Intern 1.6, you can retrieve additional command-line arguments from intern.args:
// in tests/config.js
define([ 'intern' ], function (intern) {
  return {
    proxyUrl: intern.args.proxyUrl,

    // ... additional configuration ...
  };
});

$ intern-runner config=tests/config proxyUrl=http://www.example.com:1234/

Comment: Ok thats right, but we're starting intern via grunt and thus dont provide custom arguments. Isnt there a way to set the ip / hostname dynamically via node?
Comment: You can put arbitrary arguments in the configuration in a Gruntfile as well.
Comment: Yeah but again the dev must change the grunt file then... Developers should check out and run grunt. Nothing more, ip and other dynamic config adjusting itself automatically.
Comment: I found a solution to automatically obtain local LAN ips and dynamically build the proxyUrl setting attribute for intern.js. Result to be seen below.
Answer: I found out about how to easily obtain the current LAN ip by using os.networkInterfaces() like described in nodejs documentation http://nodejs.org/api/os.html#os_os_networkinterfaces
So if needed a dynamically obtained localLan ip automatically for the static proxyUrl config flag of intern.js we just add the corresponding code within the define of e.g. your Gruntfile as Grunt itself is being executed within the nodejs environment:
/* jshint node: true*/
"use strict";
module.exports = function (grunt) {
    require("time-grunt")(grunt);

    var os = require('os');
    var interfaces = os.networkInterfaces(),
        localLanIp = null,
        setLocalLanIp = function (deviceDetails) {
            if (deviceDetails.family === 'IPv4' && !deviceDetails.internal) {
                localLanIp = deviceDetails.address;
            }
            return localLanIp !== null;
        };

    for (var device in interfaces) {
        //just check devices containing LAN or eth
        if (device.indexOf("LAN") > -1 || device.indexOf("eth") > -1) {
            //as we can'T break a forEach on arrays we use some and break on return true.
            interfaces[device].some(setLocalLanIp);
            //break outer for as loaclIp is found.
            if (localLanIp !== null) {
                break;
            }
        }
    }

    //if no ip found default to localhost anyway.
    if  (localLanIp === null) {
        localLanIp = "localhost";
    }

    grunt.initConfig({

        intern: {
            remote: {
                options: {
                    runType: "runner",
                    config: "tests/intern.js",
                    reporters: [ "console" ],
                    suites: [ "tests/module" ],
                    proxyPort: 9000,
                    proxyUrl: 'http://' + localLanIp + ':' + 9000
                }
            }
        }
    });
    grunt.loadNpmTasks("intern");
    grunt.registerTask("default", ["intern"]);
};

In my opinion defaulting to a local LAN ip would have been a good idea, but this is working great if you can't rely on localhost or 0.0.0.0 addresses but do not want to manually edit any config at all (or can't due to any reason).
Comment: This configuration file will never work since Node.js modules aren't AMD module (so loading `os` won't work, it will throw), and an `os` module does not exist in browsers, which will also load this configuration file for unit tests…
Comment: Of course, in my haste (copied parts of our more complex config) I mixed up the Gruntfile and the intern.js config... The example of course resides within the Gruntfile.js configuring intern. I will add a new Code example with the proper config. Thanks for the hint, just didn't see it while writing (should have checked the stripped example first).


How to copy Azure storage account contents (tables, queues, blobs) to other storage account

Question: I'm using Azure Durable Functions and I want to make a copy of the "production data" storage account to another storage account, to test out some things (such as data migration strategies, performance and other issues).
For that, I was hoping to find the easiest and most out of the box way, to just copy the full contents of an Azure Storage Account to another Storage Account.
Is there something out there? Or maybe a PowerShell script that can perform this?
(replication only works for blob objects)
Best regards
Answer: Azure Storage accounts are made up of 4 different types of storage: blobs, fileshares, queues and tables.  Different methods and/or strategies will be required to copy each type to a new storage account.
There are many tools you could use to automate the process including the Az PowerShell module, the az cli and the Azure REST API.  Not all tools provide methods for working with all 4 types of storage.
First you will need to create a new storage account to copy your data to.  Be aware that account names are globally unique not just unique within your tenant, are limited to 24 characters in length and can only be made up of lowercase letters and numbers.  You could use the New-AzStorageAccount PowerShell cmdlet to create the new account.
Blobs
Blob storage is made up of containers that hold blobs in a flat file structure.  You will need to recreate each container from your source account, this could be done using the PowerShell cmdlet New-AzStorageContainer.  Once the containers have been created you can use Start-AzStorageBlobCopy to copy the blobs from the container in your source account to the container in your new account.
Fileshares
The storage account can contain multiple fileshares each containing a nested folder structure of varying depth.  You can create a new file share in your destination account using New-AzStorageShare.  Once you've recreated your fileshares you'll need to recurse through the folder structure in each share to get all the files.  You can then use New-AzStorageDirectory to recreate the folder structure and Start-AzStorageFileCopy to copy the files into the new fileshare.
Queues
As queues use a publisher subscriber model and the data is transient it may be easiest to recreate the queue and use a variation on the method your current publisher uses to populate the new queue with data.  You can use New-AzStorageQueue to create the new queue.  Alternatively you could create the new queue and repoint the publisher to it and only repoint the subscripers once the old queue is drained.  For your use case the first approach may be more suitable.
Tables
The storage account can contain multiple tables each containing multiple rows of data.  You can use New-AzStorageTable to recreate the tables but this will not copy over the data they contain.  Unfortunately there isn't a cmdlet in the Az module to do this but the AzTable module contains the Get-AzTableRow and Add-AzTableRow cmdlets which should allow you to copy the rows to the new table.
Summary
In practice implementing all this will require quite a lengthy script which will only grow if you need the process to handle large volumes of data and handle errors to ensure an accurate copy.  I've developed a script that handles blobs and fileshares which was sufficiently robust and quick enough for the hobby project I needed it for.  However, it took several hours to copy around 10 accounts the largest of which contained less than 1Gb of data so probably won't scale well to a commercial environment.  The script can be found here if you wish to use it as a starting point.
Answer: Potentially you can try azcopy functionality, have a look here:
azcopy copy 'https://mysourceaccount.blob.core.windows.net/mycontainer?sv=2018-03-28&ss=bfqt&srt=sco&sp=rwdlacup&se=2019-07-04T05:30:08Z&st=2019-07-03T21:30:08Z&spr=https&sig=CAfhgnc9gdGktvB=ska7bAiqIddM845yiyFwdMH481QA8%3D' 'https://mydestinationaccount.blob.core.windows.net/mycontainer' --recursive

The example above copies the whole container from one account to another.
Comment: Is there any advantage to azcopy over the az cli (there is `az storage copy` subcommand) or the powershell az module?
Comment: It should not be, down the line they should use the same API. az cli Is more generic, while azcopy is just a tool composed for copy tasks.


Passa variável externa ou Constante para dentro de uma Função

Question: Como passar uma variável para dentro de uma função estando essa variável no lado de fora. Não sei o que mais posso fazer      .
 <?php
 $id_transfer = $_SESSION["id_transfer"];
 $ptv = $_GET["tipo"];

 /////// Função Pegar o Fornecedor//////////////
 function get_marcas() {
 $idt = IDT;
 $uf2 = UF;
 $sql = "select * from fornecedores where id_transfer = $idt  AND uf =
 '$uf2'";
 $result = mysql_query($sql) or die(mysql_error());

 $marcas = array();
 while($row = mysql_fetch_assoc($result)){
 $marcas[] = $row;
 }
 return $marcas;
 }

 /////// Função Pegar o Veiculo//////////////
 function get_modelos($id_marca,$ptv) {
 if(!ctype_digit($id_marca)) return array();

 $sql = sprintf("select * from veiculos where tipo = '$ptv' AND
 id_fornecedor = %d",
 $id_marca);
 $result = mysql_query($sql) or die(mysql_error($conexao));

  $modelos = array();
  while($row = mysql_fetch_assoc($result)){
  $modelos[] = $row;
  }
  return $modelos;
  }

  switch ($_POST['acao']) {
  case "exibeModeloSelect":
    $txt =  '<select name="id_veiculo" class="form-control">';
    $txt .= '<option value="">Selecione o Veiculo</option>';

    foreach(get_modelos($_POST['id_marca'],$ptv) as $modelo) {
        $txt .= '<option value="'.$modelo['id_veiculo'].'">' .
    $modelo['modelo'] . '  Placa: ' . $modelo['placa'] .
    '</option>';
    }

    $txt .= "</select>";

    echo $txt;
    break;
    }

       /////// Função Pegar o Motorista//////////////

   function get_cor($id_marca) {

   if(!ctype_digit($id_marca)) return array();

   $id_marca = mysql_real_escape_string($id_marca);
   $sql = sprintf("select * from motoristas where id_fornecedor = %d",
   $id_marca);
   $result = mysql_query($sql) or die(mysql_error());

   $modelos = array();
   while($row = mysql_fetch_assoc($result)){
   $cor[] = $row;
   }
   return $cor;
   }

   switch ($_POST['acao']) {
   case "exibeModeloSelect":
    $txt2 =  '
<select name="id_motorista" class="form-control">';
    $txt2 .= '<option value="">Selecione o Motorista</option>';

    foreach(get_cor($_POST['id_marca']) as $cor) {
        $txt2 .= '<option value="'.$cor['id'].'">' . $cor['nomecompleto'] .
   '  Telefone:  ' . $cor['tel'] . '</option>';
    }

    $txt2 .= "</select>";

    echo $txt2;
    break;
    }
    ?>

Comment: Há várias formas de introduzir o valor dessa variável no escopo da função, como podes ver nas respostas abaixo, exemplificam várias formas de o fazer. Para que seja mais claro e objetivo, podes dizer de onde provém o valor dessa variável ? Ou de onde queres que ela venha ?
Comment: Essa variável vem de uma outra consulta que me lista o tipo de veiculo
Comment: Okay, é possível editares a pergunta e adicionares também essa outra parte ?
Comment: coloquei o codigo completo mais não coloquei  a consulta pois ficaria muito grande o codigo aqui, mais coloquei la em cima uma essa variavel como se estivesse vindo de um $_GET que daria no mesmo
Comment: Eu só queria que o where tipo = '$ptv   pega-se essa variavel #$ptv
Comment: Olha, comenta o resto do código, e faça: `print($ptv)` ou `echo $ptv`. E diga o que retornou.
Comment: Esta retornando  Van
Comment: Obs na primeira função "function get_marcas() { "   eu consigo colocar variaveis la dentro vindo de constantes mais na segunda nem as constante funcionam.
Comment: Já experimentaste retornar o valor de `$_POST['id_marca']` ? Olha, se possível, coloca o código todo no _pastebin_ juntamente com as tabelas em uso.
Answer: Mude a assinatura da função adicionando o novo parâmetro e se quiser defina um valor padrão.
function get_modelos($id_marca, $ptv=10) {

Depois basta chamar:
get_modelos($id_marca, 'van');

Answer: segundo a documentação neste link, existem algumas formas de se fazer
<?php

  $a = 1; /* escopo global */

  function Teste()
  {
    echo $a; /* referencia uma variável do escopo local (não definida) */
  }

  Teste();
?>

ou ainda utilizando as váriaveis globais
<?php
  $a = 1;
  $b = 2;

  function Soma()
  {
      global $a, $b;

      $b = $a + $b;
  }

  Soma();
  echo $b;
?>

mas acho que é a mais sensata é passar a variável como parâmetro da função
<?php
  $ptv = 'Van';//   Essa é a variavel que entrar no Where do select

  function get_modelos($id_marca,$ptv) {

    if(!ctype_digit($id_marca)) return array();
    $sql = sprintf("select * from veiculos where tipo = '$ptv' AND
    id_fornecedor = %d", $id_marca);
    $result = mysql_query($sql) or die(mysql_error($conexao));

    $modelos = array();
    while($row = mysql_fetch_assoc($result)){
      $modelos[] = $row;
    }
    return $modelos;
  }
?>

Todos estes exemplos estão no link acima...
Comment: Testei neste ultimo exemplo e deu este erro... Warning: Missing argument 2 for get_modelos(), called in
Comment: Quando vc chamouba função vc passou o segundo parâmetro? `get_modelos($id_marca,$ptv)` mas lembre-se de iniciar a variável e ter certeza que ela é válida...


Apache Beam State Management/Processing - Sharing State across ParDo at the Window Scope?

Question: My Dataflow pipeline collates event data into typed per session and per user PCollections output. I have employed GroupByKey for events keyed by session id. Sessions are grouped into parent types keyed by user id and device id using the same pattern at this next level of hierarchy. So a single session might generate many events, but in turn a single user might generate many sessions.
I would now like to summarize this data across each level of the hierarchy. I have used a StateSpec declaration to persist state at the event level. So for example, an event count property can be incremented in my event processing ParDo. (Use Case : generating an error event per session across all users for example.)
But as each ParDo is static - I cannot access the ValueState outside of the ParDo context even though my understanding is this state is maintained at the Window scope. (Maybe this is by design.) Is there a way to access this Window level state using the Beam State persistence lib in another ParDo than where it was originally declared? Like as if I could declare it at the pipeline level?
I understand that this may introduce some performance overhead as the framework must manage concurrency, but the actual processing seems negligible. (Just incrementing values.) So I would prefer to write this to a window level state field rather than percolate values up via my hierarchy.
Comment: So after spending hours isolating and working at a StatSpec based solution I am abandoning this approach. I don't fully understand why, but I am only able to write to StatSpec ValueState in the first .apply in my pipeline. Later in my pipeline there is a race condition where the .write call does appear to work within the context of the ParDo, but then subsequent reads in the ParDo return null. So perhaps I am misunderstanding something about the API or there is a bug. I'm not sure. Perhaps this happens after I perform a GroupByKey and this affects the StatSpec scope somehow.
Comment: There was always going to be a bottleneck writing to a single StatSpec and so I will attempt to summarize values in another downstream aggregator.
Answer: State sharing cross ParDos is not supported, and it shouldn't even be encouraged as it brings dependencies among ParDos that breaks the simple contract: ParDo can work on PCollection independently thus unblocks massive parallelism.
Comment: Yes ok. I understand the rationale for discouraging this practice, but it would be nice to have the extra flexibility if there is no reason the implementation cannot support it. Perhaps with suppressible warnings.
Comment: Perhaps this is a case of implementation constraints that improved my overall design. I am still learning. But letting me flail around a little more with a less complex, albeit suboptimal solution only makes you more money right? ha :)


Proving that $f\left(\frac{x+y}{2}\right) \le \frac{f(x)+f(y)}{2}$ is convex

Question: I'm trying to prove:

$f$ is a continuous real function defined in $(a, b)$ such that $$f\left(\frac{x+y}{2}\right) \le \frac{f(x)+f(y)}{2}$$ for all $x, y \in (a, b) \implies f$ is convex.

I was also given:

A real function $f$ defined in $(a, b)$ is said to be convex if $$f(\lambda x+(1-\lambda)y) \le \lambda f(x)+(1-\lambda)f(y)$$ whenever $a < x, y < b, 0<\lambda < 1$.

My attempt at a proof:  Let $x, y \in (a, b)$ and take $f$ be a continuous real function defined in $(a, b)$ such that $$f\left(\frac{x+y}{2}\right) \le \frac{f(x)+f(y)}{2}.$$ Now, suppose to the contrary that $\exists x, y \in (a, b), \lambda \in (0, 1)$ such that $$f(\lambda x+(1-\lambda)y) > \lambda f(x)+(1-\lambda)f(y).$$ We claim that the equation above os satisfied if we take $\lambda = 0.5$, that is, we obtain $$f\left(\frac{x+y}{2}\right) > \frac{f(x)+f(y)}{2}$$ which contradicts the definition of $f$.
Can someone please proofread this proof and let me know if it is accurate? If not, please just point out the error(s); please don't bother to suggest a new proof of this problem.
Comment: Does this answer your question? [Midpoint-Convex and Continuous Implies Convex](https://math.stackexchange.com/questions/83383/midpoint-convex-and-continuous-implies-convex)
Comment: @Integrand Judging by the last sentence, I would say it does not.
Answer: There is a rather serious error: you are concluding from your assumption of non-convexity that there is some $\lambda \in [0, 1]$ and $x, y$ such that
$$f(\lambda x + (1 - \lambda)y) > \lambda f(x) + (1 - \lambda)f(y).$$
This is fine, but then next you assume that this $\lambda = 1/2$. This assumption is erroneous. You can only assume $\lambda \in [0, 1]$, not any specific value of $\lambda$ you wish.
You will absolutely need the continuity assumption too; there are discontinuous counterexamples!
Comment: This is exactly what I had suspected, but I just wanted to be sure, thanks!


How to find the last 10 rows of first two columns in a data frame using python

Question: I want to access the last 10 rows of the first two columns of a data frame in python called index
index.tail(10).index.iloc[:,0:2]

But I get the following error:
RangeIndex' object has no attribute 'iloc

Comment: what library are you using for your dataframe?
Answer: https://colab.research.google.com/drive/12fg1MpIJeVM03-DGgLr39v4D1k97bR10
import pandas as pd
df = pd.DataFrame({"datax": range(10, 64, 8),
"datay": range(0, 84 ,12)}) # 2 columns with 7 data points

print(df) # print dataset
print(df.iloc[-2:,:1])
# get last two rows of the first column using iloc

You can use iloc to perform advanced indexing on dataframes. An example can be found on the Colab link I have shared.
Answer: To find the last 10 rows of first two columns in a data frame using python you can use:
df.iloc[-10:, 0:2]

Comment: I think this is an attempt to answer.


How do i get passed an empty key in a php array

Question: how to i get to the arrays content if it doesnt have a key like this
<code>$products[0]
</code>
this will get me partially there but how to i get past []
<code>( [0] => Array
( [] => Array (
[0] => Array ( [product_name] => stuff i need to get to  )
</code>
Answer: That is very strange. You could try
<code>$products[0][''][0]['product_name']
</code>
Comment: Good idea. It's likely that the code generating this array has a typo or something that's setting the key to the empty string. Of course, you may also need to append `['product_name']` to this answer to get all the way to the 'stuff i need ...'
Comment: @grossvogel: oops, yeah I missed that out.
Answer: <code>$products[0][""][0]["product_name"]
</code>
Answer: Use var_dump or var_export to print your array and you will see its an empty string.
print_r will give you output like that for empty strings.


Changing "add new node" button

Question: I have a content type "consultation" that has an inline entity reference to 1 node of a content type "prescription". This content type prescription has multiple inline entity references to the content type "medecine".
I'm using the module Inline Entity Form so I create/add all of these nodes in the creation form of "consultation".
I'm trying to change the text "Add new node" in the form to something else. I know how to do this when it's a direct entity reference, but how do I get to the "Add new medecine" for "medecine"?
This is my code so far:
<code>function node_change_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'consultation_node_form':
  $form['field_prescription_med']['und']['actions']['ief_add']['#value'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['#title'] = t('Add new medecine');
  $form['field_prescription_med']['und']['form']['actions']['ief_add_save']['#value'] = t('Add new medecine');
  break;
}}
</code>
In this code:

field_prescription is the name of the entity reference field in "consultation" (to a "prescription")
field_prescription_med is the name of the entity reference field in "prescription" (to "medecine")
Answer: You can use hook_field_widget_WIDGET_TYPE_form_alter() to alter the button name
example:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function example_field_widget_inline_entity_form_form_alter(&$element, &$form_state, $context) {
  // Rename the button in specific form.
  if($form_state['build_info']['form_id'] == 'eck__entity__form_edit_sample_sample') {
    $element['actions']['ief_add']['#value'] = t('Add new medecine');
  }
}
Comment: What formid should I use in my case? I thought it'd be consultation_node_form, but that doesn't seem to change anything (nor does prescription_node_form). The heading I use is: function my_module_inline_entity_form_form_alter(&$element, &$form_state, $context) which is correct I assume?
Comment: Ah, it was function my_module_field_widget_inline_entity_form_form_alter
Comment: you can check the value of your form id by dumping $form_state['build_info']['form_id'], inside your function print "" . var_dump($form_state['build_info']['form_id']) . "";  or if you have devel module installed in your drupal project you can use dpm($form_state['build_info']['form_id'])

Changing "add new node" button


Set node action for specific content type

Question: I want to set a trigger to redirect when a node (or comment) on a certain content-type is created.
I have 2 hurdles here:

The Trigger module doesn't seem to offer any distinction between content types. Will I have to write some sort of hook?
I can create an action to redirect to the specific URL, but it always shows up under the 'system' category and is then not in the dropdown list when I go to set it for creation of every content type.
Answer: The Rules module will be able to handle this, it's a next-generation version of the actions/triggers that are included with core:

The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

You can use the "After saving a new comment" event for the comments part, and the "After saving new content" event for the content part.
In both cases you'll be able to use conditions on your rules to make sure the actions are only fired for your required content types.


how to make a shell execute with suid

Question: I'm trying to suid a shell and it's not working.  I need help understanding why, and how to fix it...
I'm following these steps (as root)
cp /usr/bin/bash /usr/bin/bash-emergency
chmod 4755 /usr/bin/bash-emergency

bash-emergency is owned by root:root
I would expect that this should execute bash-emergency as root, resulting in a root shell
I know all the reasons not to do this.  This is in a lab.  su and sudo, for the sake of this test, are not an option.  I need a user to be able to get a root shell without having to authenticate or otherwise be challenged after their initial login.
I'm hoping to be able to do this with a simple suid executable rather than changing the non-root user's UID to 0.
What am I doing wrong?
Comment: You are doing nothing wrong other that breaking all security measures on the system and possibly on the network. When you execute your suid binary, what is the output of the `id` command?
Comment: what are you trying to solve? looks for me like a homework
Comment: @doneal24 the output is 'uid=1000(ec2-user) gid=1000(ec2-user) euid=0(root) groups=1000(ec2-user),4(adm),10(wheel),190(systemd-journal)'  Notice the EUID is 0, but the UID is still my rergular UID.  In this condition, some commands run as root (ie. touch x), but programs that actually check for root give the message "You must be root to run this command."
Comment: @djdomi Definitely not homework.   I am setting up a Unix class environment where the students will have direct access to root -- including the ability to render su and sudo useless.  I won't really have a way to get to the console, boot into single-user mode, and fix them.  My goal here is, hoping the students haven't also broken ssh, that I can pop in and use an "emergency shell" to fix the damage they did... ie broken pam, broken sudoers, etc.  This happened the last time I taught the class... just trying to find a way to fix it if it happens again.
Comment: The behavior seems consistent with bash and ksh, so I don't think it's shell-specific.
Comment: Just a bump -- anyone have any ideas?  Thank you!
Answer: What you are doing wrong is running face-first into a security measure designed to keep the system safe. Bash, dash, and other shells detect that they're being run setuid root and immediately drop privileges on launch. This is because setting them suid root is a very common privilege escalation tactic.
Fortunately, there's a really easy work around for you. Launch your suid shell as /usr/bin/bash-emergency -p.
Relevant quote from the docs:

If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.
Comment: Thank you for the tip.   Unfortunately, the behavior is the same with or without the -p with respect to privilege.  I can touch a file and it will be owned by root, as expected, but if an application specifically tests if the user running it is root, it still fails because the UID doesn't get set to zero.
Comment: Is `/usr/bin/bash-emergency` owned by root? Nevermind, answered in the original post.
Comment: Yes, you have root privileges, and can do root things, but you'll still be your previous user. You can still fix /etc/passwd, /etc/shadow, /etc/sudoers, /root/.ssh and so forth. If you need full root shell for something, it's best to bootstrap yourself back to a proper root shell using one of those. I can drop another answer on how to compile a binary that will do it in a single step if you like.
Comment: That would be interesting to see.   Thank you.
Answer: While shell programs deliberately don't do what you want, you could create your own program that does. This is an example program that will check if you have euid root, and if so, run a specific command as uid root.
Usage is something like /usr/bin/emergency-backdoor /usr/bin/bash, or /usr/bin/emergency-backdoor "/usr/bin/vim /etc/passwd", and so forth.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        puts("Usage: <this> \"command and args\"");
        return 1;
    } else if (geteuid() == 0) {
        setuid(0);
        setgid(0);
        puts("Executing the following as root");
        puts(argv[1]);
        system(argv[1]);
    } else {
        puts("You do not have privs");
    }
    return 0;
}

how to make a shell execute with suid


Is it true that $\text{Var}(X)=\mathbb E[(X-Y)_{+}^{2}]$ for $Y$ iid to $X$

Question: Is it true that $\text{Var}(X)=\mathbb E[(X-Y)_{+}^{2}]$ if $X$ and $Y$ are independent identically distributed?
Note that $(X-Y)_{+}^{2}$=$(X-Y)^{2}\chi_{\{X\geq Y\}}+0\chi_{\{X< Y\}}$
Why is this true? Any proof?
Comment: Yet another closed question that makes no sense ...please vote to reopen
Comment: @TheBridge the question contains no context. For example, is it a question from a book or course, and if so what was covered in the preceding chapter or lecture?
Comment: The Question is clear there are all tags needed to get it after this if you need more context then what about just ignoring  the post ?
Answer: Hint: $E(X-Y)^{2}_{+}=E(X-Y)^{2}I_{X \geq Y}=E(Y-X)^{2}I_{Y \geq X}$  because $(X,Y)$ is i.i.d. Hence, $E(X-Y)^{2}_{+}=E(X-Y)^{2}I_{Y \geq X}$ which shows that $E(Y-X)^{2}I_{Y \geq X}=\frac  1 2 E(X-Y)^{2}$. Now you can complete the proof by expanding $(X-Y)^{2}$.
[It should be noted that $E(X-Y)^{2}I_{X=Y}=0$]
Comment: Why is the downvoting?
Comment: I feel like $P(X=Y)$ being positive would throw a spanner in the works here.
Comment: @Arthur No. $(X-Y)^{2}=0$ when $X=Y$ so my argument works.


Error with XKCD comic scraping program

Question: Following the "Automate the boring stuff" book, I've written a script to download every xkcd comic. I've followed the code from the book exactly(as far as I can tell), but I'm receiving an error I don't understand.
Link
Traceback:
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/ericdusseau/PycharmProjects/AutomateTheBoringStuff/downloadXkcd.py
Downloading page http://xkcd,com...
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connection.py", line 141, in _new_conn
    (self.host, self.port), self.timeout, **extra_kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/util/connection.py", line 60, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py", line 356, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connection.py", line 166, in connect
    conn = self._new_conn()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connection.py", line 150, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.HTTPConnection object at 0x104f80240>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/adapters.py", line 423, in send
    timeout=timeout
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/connectionpool.py", line 649, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/packages/urllib3/util/retry.py", line 376, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='xkcd,com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x104f80240>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/ericdusseau/PycharmProjects/AutomateTheBoringStuff/downloadXkcd.py", line 11, in <module>
    res = requests.get(url)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/requests/adapters.py", line 487, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='xkcd,com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x104f80240>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

Process finished with exit code 1

SourceCode:
#! python3
# downloadXKCD.py - Downloads every single XKCD comic.

import requests, os, bs4

url = 'http://xkcd,com'             #starting url
os.makedirs('xkcd', exist_ok=True)  # store comics in ./xkcd
while not url.endswith('#'):
    #Download the page
    print('Downloading page %s...' % url)
    res = requests.get(url)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text)

    #Find the URL of the comic image.
    comicElem = soup.select('#comic img')
    if comicElem == []:
        print('Could not find comic image.')
    else:
        try:
            comicUrl = 'http:' + comicElem[0].get('src')
            #Download the image.
            print('Downloading image %s...' % (comicUrl))
            res = requests.get(comicUrl)
            res.raise_for_status()
        except requests.exceptions.MissingSchema:
            #Skip this comic
            prevLink = soup.select('a[rel="prev"]')[0]
            url = 'http://xkcd.com' + prevLink.get('href')
            continue

    #Save the image to ./xkcd
    imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb')
    for chunk in res.iter_content(100000):
        imageFile.write(chunk)
    imageFile.close()

    #Get the Prev button's url.
    prevLink = soup.select('a[rel="prev"]')[0]
    url = 'htt[://xkcd.com' + prevLink.get('href')

print('Done.')

Comment: `url = 'http://xkcd,com'`  That should be `.com`, not `,com`
Comment: I can see several redefinition of the base url. Moreover, at the bottom of your code, your url seems malformed: `htt[://`.
Answer: Your output gives you an idea where the problem lies:
Downloading page http://xkcd,com...
Traceback (most recent call last):

http://xkcd,com is an invalid URL. It should be .com, not ,com.

Speaking of incorrect URLs, you also have another invalid one later in your code:
url = 'htt[://xkcd.com' + prevLink.get('href')
          ^ Should be 'p'

Answer: I made a few changes to the code in "Automate the boring .." book and dont see issues even if there are no images
 try:
        elem = requests.get('https://xkcd.com/')
        elem.raise_for_status()
   except Exception as esc:
        print('exception in search:%s' %(esc))
elemSoup = bs4.BeautifulSoup(elem.text,'html.parser')
elemSouplink = elemSoup.select('.comicNav a')
  # print('elements:'+str(elemSouplink))
while (not (elemSouplink[1].get('href')=='/1/')):
   prev= elemSouplink[1].get('href')
  # print('prev:'+str(prev))
   elem=requests.get('https://xkcd.com'+prev)
  # print('new link:https://xkcd.com'+prev)
   elemSoup = bs4.BeautifulSoup(elem.text,'html.parser')
   elemSouplink = elemSoup.select('.comicNav a')

Answer: There is a comma in xkcd,com. Not a dot...
Answer: There is a git repository having a script that downloads a random xkcd comic image and set that image as a wallpaper. You can set that in cron for every minute so that it will change the desktop wallpaper:
xkcd_random_wallpaper

Error with XKCD comic scraping program


derivatives manipulations

Question: How to show this:
$f(x,y+en,y'+en')-f(x,y,y')= en(df/dy)+e(dn/dx)(df/dy')+O(e^2)$
y and n are functions of x, e small constant
And y is smooth.
What identities or properties are used here?
Answer: You did not give any assumptions on $f$. It suffices to assume that the first-order partial derivatives of $f$ are continuous, and second-order derivatives are bounded (in a neighborhood of the point of interest). Then the following form of multivariable Taylor expansion holds:
$$
f(u,v,w) = f(u_0,v_0,w_0) + \frac{\partial f}{\partial u}(u_0,v_0,w_0)\,(u-u_0) +
\frac{\partial f}{\partial v}(u_0,v_0,w_0)\,(v-v_0) + \frac{\partial f}{\partial w}(u_0,v_0,w_0)\,(w-w_0)
+O\left((u-u_0)^2+(v-v_0)^2+(w-w_0)^2\right)
$$
In your situation $u=u_0=x$, $v_0=y$, $v=y+e n$, $w_0=y'$, $w=y'+en' = y'+e(dn/dx)$. This yields the identity.

derivatives manipulations


Elements shouldn`t duplicate

Question: I have programmed a quiz, there I created an array of the questions,  choices and the answer. The Arrays are in the QuestionLibrary. In my main activity (Quiz Activity) I randomize the questions, after every correct answer the questions appear in random rows. It works fine, I only don`t want that the questions do not repeat them self like: "What is my name", "how are you" "What is my name". They should only appear ONCE. For Example, there are 13 questions, I want that every question will be only asked only once but in random orders and not several times. How can I set that up? (I am beginner)
Quiz Activiy:
<code>    package amapps.impossiblequiz;

       import android.content.Intent;
       import android.os.Bundle;
       import android.support.design.widget.NavigationView;
       import android.support.v4.widget.DrawerLayout;
       import android.support.v7.app.ActionBarDrawerToggle;
       import android.support.v7.app.AppCompatActivity;
       import android.support.v7.widget.Toolbar;
       import android.view.MenuItem;
       import android.view.View;
       import android.widget.Button;
       import android.widget.TextView;
       import android.widget.Toast;

       public class QuizActivity extends AppCompatActivity {

private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private MenuItem menuItem;
private Intent in;

private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;

private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);

    //Randromize the row of the questions
    QuestionLibrary q = new QuestionLibrary();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
    q.shuffle();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));

    //End randomizer

    mToolbar = (Toolbar) findViewById(R.id.nav_action);

    setSupportActionBar(mToolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"

    NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case(R.id.nav_stats):
                    Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
                    startActivity(accountActivity);
            }
            return true;
        }
    });

        mScoreView = (TextView) findViewById(R.id.score_score);
        mQuestionView = (TextView) findViewById(R.id.question);
        mButtonChoice1 = (Button) findViewById(R.id.choice1);
        mButtonChoice2 = (Button) findViewById(R.id.choice2);
        mButtonChoice3 = (Button) findViewById(R.id.choice3);

        updateQuestion();

        //Start of Button Listener1
        mButtonChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice1.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();

                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);

                }
            }

        });
        //End of Button Listener1

        //Start of Button Listener2
        mButtonChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice2.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();

                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);

                }
            }

        });
        //End of Button Listener2

        //Start of Button Listener3
        mButtonChoice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice3.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();
                    mQuestionLibrary.shuffle();

                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);

                }
            }

        });
        //End of Button Listener3

    }

private void updateQuestion() {

    if (mQuestionNumber < mQuestionLibrary.getLength()) {
        mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));
        mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));
        mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));

        mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
        mQuestionNumber++;
    }
    else {
        Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(QuizActivity.this, Menu2.class);
        intent.putExtra("score",mScore); //pass score to Menu2
        startActivity(intent);

    }

}

    private void updateScore ( int point){
        mScoreView.setText("" + mScore);

    }

    @Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
    public boolean onOptionsItemSelected (MenuItem item){
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
</code>
Question Library:
<code>    package amapps.impossiblequiz;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public class QuestionLibrary {

private final String[] [] mChoices ={
        {"1993", "1986", "1967"},
        {"-260", "-272,15", "279,15"},
        {"a plant","The active substance of marijuana" , "a spider"},
        {"6", "10","8"},
        {"12","15","10"},
        {"Uranus","Neptune","Saturn"},
        {"HCl","NaCl","CO"},
        {"John F. Kennedy", "Richard Nixon","James A. Garfield"},
        {"Canada","Denmark", "Greenland is an own state?"},
        {"12","20","14"},
        {"10","12","14"},
        {"not","never","now"},
        {"Leningrad","Wolgograd","Dimitrijgrad"}

};
private final String mQuestions[] = {
        "When was the European Union founded?",
        "How many Grad Celsius is one Kelvin?",
        "What is THC?",
        "How many legs has a spider?",
        "How many stars has the European flag?",
        "Which is the seventh planet from the sun?",
        "What is the chemical formula of salt?",
        "Who said: Ich bin ein berliner?",
        "To which country belongs Greenland?",
        "What is the result of: 2 + 2 *5?",
        "How many mountains are higher than 8000 meter/26.246 ft?",
        "A famous quote is: to be, or____ to be!",
        "What is the name of Stalingrad nowadays?"

};

private final String mCorrectAnswers[] = {
        "1993", "-272,15", "The active substance of marijuana",
        "8", "12","Uranus","NaCl","John F. Kennedy",
        "Denmark","12","14","not","Wolgograd"

};

private final List<Integer> indexes = new ArrayList<>();

public QuestionLibrary() {
    for (int i = 0; i < mQuestions.length; ++i)
        indexes.add(i);
}

private int index(int i) {
    return indexes.get(i);
}

public String getQuestion(int a) {
    return mQuestions[index(a)];
}

public String getChoice1(int a) {
    return mChoices[index(a)][0];
}

public String getChoice2(int a) {
    return mChoices[index(a)][1];
}

public String getChoice3(int a) {
    return mChoices[index(a)][2];
}

public String getCorrectAnswer(int a) {
    return mCorrectAnswers[index(a)];
}

public int getLength() {
    return mQuestions.length;
}

public void shuffle() {
    Collections.shuffle(indexes);
}
}
</code>
Comment: Just remove all the `mQuestionLibrary.shuffle();` calls? You are already shuffling once at the beginning: `q.shuffle();`.  That gives your random order. You don't then need to shuffle *again* after every answer.
Comment: In your Question library, maintain a list or index of already asked questions in an array and just check if that is being repeated, then get another one.
Comment: @kapsym you probably meant a set of indices not a list
Comment: Hello well thats problably the best way... how can I set up  that it shuffles only one time? on beginning of the new Activity?
Comment: @efekctive yep a set or even a array can be used if used correctly. Matter of preference
Comment: @ProjectX As I mentioned have an array or a Set called AlreadyAskedQuestions and before populating the next question, just check if the question is already there in your AlreadyAskedQuestions Collection, If its there don't ask that question and move to next one. Also as Mr Spoon mentioned that you need to do q.shuffle just once to start with a random set of questions. You will still need the AlreadyAskedQuestions because if your activity closes in between then your questions will start again.
Comment: I already solved it but thanks for your help! I solved it like your technique
Answer: Shuffle the collection once when you load the activity, rather than after every time a question is answered.
Comment: Remove all the `mQuestionLibrary.shuffle();` from the button onClick listeners. Looks like you already have one in the onCreate so leave that one and it should work
Comment: Now the row of the questions is every tme the same
Comment: I solved it... i only pasted mQuestionLibrary.shuffle(); at the beginning andnow it works fine thanks bro! :D

Elements shouldn`t duplicate


Dificuldades com flex-box, alinhar na direita o icone do menu

Question: Eu tive que usar flexbox para deixar a classe logo e classe menu alinhadas verticalmente no centro da tag nav porque os icones do font-awesome não estavam funcionando com line-height, porém isso está me causando problemas para construir o menu aberto, preciso que o icone menu fique no lado direto e não no esquerdo.

HTML

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="style.css">

      <title>VM Design</title>

          VM

Home

Sobre

Projetos

Fale Comigo

CSS:
* {
    padding: 0;
    margin: 0;
    font-family: 'Open Sans', sans-serif;
}

:root {
    --texto-branco: #f2f2f2;
    --fundo-preto:#262626;
    --fundo-azul:#009DFF;
}

nav {
    position: absolute;
    top: 0;
    left: 0;
    height: 64px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: var(--fundo-preto);
    box-sizing: border-box;
}

.logo {
    margin: 16px;
}
.menu {
    margin: 16px;
    display: none;
    cursor: pointer;
    color: var(--texto-branco);
}

ul {
    display: flex;
}

li {
    padding: 0 16px;
    transition: 0.3s;
    text-align: center;
}
li:hover {
    background-color: var(--fundo-azul);
}

a {
    text-decoration: none;
    color: var(--texto-branco);
}

@media  (max-width: 480px) {
    .menu {
        display: block;
        justify-self: right;
    }
    /* ---MENU FECHADO--- */
    /*li:not(:last-child) {
        display: none;
    }*/

    /* ---MENU ABERTO--- */
   .logo {
       display: none;
   }

    ul {
        margin-top: 160px;
        position: absolute;
        width: 100%;
        display: block;

    }

    ul li{
        background-color: var(--fundo-preto);
    }

}

Answer: Basta dar margin-left: auto na div.menu, assim ela cria uma margem a esquerda (left), que vai "empurrar" o menu para direita.
A propriedade justify-self: right; não funciona dessa forma, a não ser que vc esteja usando grid

<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

    VM

Home

Sobre

Projetos

Fale Comigo


Find the compenstor of the standard ito integral

Question: Let $B_t$ be a Brownian motion and let $\{\mathcal F_t : a<t<b\}$ be a filtration such that for each $t$ we have that $B_t$ is $\mathcal F_t$ measurable and for and $s<t$, the random variable $B_t-B_s$ is independent of the sigma field $\mathcal F_s$. Lastly let $L_{ad}^2[(a,b)\times \Omega]$ be this set of stocastic processes $f(t,\omega)$ such that $\int_a^bEf(s)^2 \, ds < \infty$ and $f(t,\omega)$ is adapted to the filtration $\mathcal F_t$

Consider $M_t$ = $\int_a^bf(s) \, dB(s)$. Then it is known that $M_t$ is a martingale and also $M_t^2$ is a submartingale. The Doob-submartingale decomposition says that there exists an increasing and right continuous random variable $\langle M \rangle_t$ such that $M_t^2- \langle M \rangle_t$ is a martingale. Find $\langle M \rangle_t$

I am told that $\langle M \rangle_t=\int_a^bf(s)^2ds$. Here is what I have done in order to show this.
Let $k<t$.
\begin{align*}& E\left[\left(\int_a^tf(s)\,dB(s)\right)^2 - \int_a^tf(s)^2 \, ds\mid\mathcal F_k\right] \\ &= E\left[\left(\int_a^kf(s)dB(s)+\int_k^tf(s)\,dB(s)\right)^2 - \int_a^tf(s)^2 \, ds\mid\mathcal F_k\right]
\\ &= E\left[\left(\int_a^kf(s)\,dB(s)\right)^2+\left(\int_k^tf(s)\,dB(s)\right)^2 \mid \mathcal{F}_k \right] \\ &\quad +2 E\left[ \int_a^kf(s)\,dB(s)\int_k^tf(s)\,dB(s) - \int_a^tf(s)^2\,ds\mid\mathcal F_k\right]
\\ &= \left(\int_a^kf(s)\,dB(s)\right)^2 - \int_a^kf(s)^2 \, ds \\ &\quad +E\left[\left(\int_k^tf(s)\,dB(s)\right)^2+2\int_a^kf(s)\,dB(s)\int_k^tf(s)\,dB(s) - \int_k^tf(s)^2 \, ds\mid\mathcal F_k\right] \end{align*}
where the last equality follows from the definition of our filtration. Now I'll focus on the remaining conditional expectation term. For the following I will use the independence of the increments of the Brownian motions and the fact that $E\left[\left(\int_a^bg(s) \, dB(s)\right)^2\right]=\int_a^bE(g(s)^2) \, ds$ and $E\left[\int_a^bg(s) \, dB(s)\right]=0$ I get
\begin{align*} &E\left[\left(\int_k^tf(s) \, dB(s)\right)^2+2\int_a^kf(s) \, dB(s)\int_k^tf(s) \, dB(s) - \int_k^tf(s)^2 \, ds\mid\mathcal F_k\right]  \\ &= \int_k^tE(f(s)^2) \, ds +0-\int_k^tE(f(s)^2\mid\mathcal F_k) \, ds \end{align*}
Now putting everything together we see that
\begin{align*} &E\left[\left(\int_a^tf(s) \, dB(s)\right)^2 - \int_a^tf(s)^2 \, ds\mid\mathcal F_k\right] \\ &=\left(\int_a^kf(s) \, dB(s)\right)^2 - \int_a^kf(s)^2 \, ds + \int_k^tE(f(s)^2) \, ds -\int_k^tE(f(s)^2\mid\mathcal F_k) \, ds. \end{align*}
If the last two terms cancelled each other out, i.e. $$\int_k^tE(f(s)^2) \, ds =\int_k^tE(f(s)^2\mid\mathcal F_k) \, ds$$ then we would be done and we would then see that $$\int_a^tE(f(s)^2) \, ds -\int_a^tE(f(s)^2\mid\mathcal F_k) \, ds$$ is a martingale. But im not sure that these terms do cancel each other out. So did I make a mistake somewhere above?
Answer: When dealing with the remaining conditional expectation term, you forgot to take the conditional expectation of one ingredients, namely of
$$\left( \int_k^t f(s) \, dB_s \right)^2.$$
In your calculation you seem to use that
$$\mathbb{E} \left( \left[ \int_k^t f(s) \, dB_s \right]^2 \mid \mathcal{F}_k \right) =  \mathbb{E} \left( \int_k^t f(s)^2 \, ds \right)$$ but this fails to hold true; it should read
$$\mathbb{E} \left( \left[ \int_k^t f(s) \, dB_s \right]^2 \mid \mathcal{F}_k \right) =  \mathbb{E} \left( \int_k^t f(s)^2 \, ds \mid \color{red}{\mathcal{F}_k} \right)$$
instead, see this question for a proof. Fixing this mistake will immediately solve your problem.
Comment: My mistake was that I incorrectly assumed that $\left( \int_k^t f(s) \, dB_s\right)^2  $ was independent of $\mathcal F_k$. I just read through the question you referenced and saw what you did there. Using those same techniques is it true that we can then further prove that $$ E\left(\int_k^tf(s)dB(s)\int_k^tg(s)dB(s) \; \vert \; \mathcal F_k\right) = E\left(\int_k^tf(s)g(s)ds \; \vert \; \mathcal F_k\right) $$.
Comment: @alpastor Yes, that's an immediate consequence... just use the polarization identity $$xy = \frac{1}{4}((x+y)^2-(x-y)^2)$$ for $$x \hat{=} \int_k^t f(s) \, dB_s \qquad y \hat{=} \int_k^t g(s) \, dB_s$$
Comment: Cool thank you, you're always very helpful!
Comment: @alpastor Glad I could help you; you are welcome.
Comment: I have one more question about this. Why isnt $\left( \int_k^t f(s) \, dB_s\right)^2$ independent of $\mathcal F_k$? Are there situations where this could be true? Would it be true if we could represent  $\left( \int_k^t f(s) \, dB_s\right) =\lim\limits_{\Vert \Delta_n \Vert \to 0} \sum_{i=1}^nf(t_{i-1})(B(t_i)-B(t_{i-1})$, where this limit means $L^2$ convergence. Also can we say $\left( \int_s^kf(s) \, dB_s\right)$ is independent of $\left( \int_k^t f(s) \, dB_s\right)$ for $sk$ independent of $\mathcal{F}_k$, then the stochastic integral $\int_k^t f(s) \, dB_s$ is independent of $\mathcal{F}_k$, note that this is, in particular, the case if $f$ is deterministic. If $f(s)$, $s>k$, is not independent of $\mathcal{F}_k$, then the stochastic integrals fails in general to be independent of $\mathcal{F}_k$ ... just consider for instance $f(s) := B(s)$.


Can FileMaker Server v11 support FileMaker v9 clients?

Question: See title.  Apparently FMServer v8 won't run on 10.6.x, so will upgrading the server component be sufficient or will we need to update all the v9 client licenses as well?
Answer: With the latest updates to both (FMServer 11v2 and FM 9v3), apparently the answer is 'yes'.
Answer: We're running FMServer 11v2 on our 10.6 server, with our FM 8.5 clients on 10.4.11 without problems.