Erro NullPointerException na execução

Question: Olá. Mais uma vez estou tendo erro de  NullPointerException. Não consigo identificar porque.
A Atividade é a seguinte :

Crie um aplicativo Java para controlar o cardápio semanal de pacientes de uma Clínica de Nutrição. Você deverá considerar a criação de duas classes, sendo:
Classe Refeição: contém a descrição da refeição, bem como as informações de valor calórico, custo aproximado e tipo da refeição. O tipo da refeição é uma classificação estabelecida pela clínica, conforme:
Diet;
Equilibrada;
Light;
Low carb;
Low fat;
Natural;
Sem glúten;
Vegano;
Vegetariano;
Classe Cardápio: que deverá conter o cardápio semanal, com 6 refeições diárias.
Crie uma classe Teste (com o método main()) para gerar um cardápio semanal que calcule o custo e valor calórico diários e semanal do cardápio.
Observações importantes:
Para implementar o tipo das refeições, considere a criação de um array estático na classe Refeição com os valores acima descritos.
  Na classe Cardápio, implemente as operações de manipulação do array bidimensional (incluir, alterar, percorrer, e etc).
  Excepcionalmente nesse projeto, o método de exibição do cardápio semanal da classe Cardápio poderá exibir mensagens na console. Evite fazer isso nos demais métodos e nas demais classes, exceto na classe de Teste.

Classe RestauranteTeste:
public class RestauranteTeste {

    public static void main(String[] args){

        Cardapio semana = new Cardapio();

        semana.incluirRefeicao();

    }//end main method

}//end class RestauranteTeste

Classe Refeicao:
package projeto_4;

public class Refeicao {

    //Atributos da Classe
    private String descricao;
    private int caloria;
    private double custo;
    private int tipoDeRefeicao;

    //atributo estatico inicializado com os valores pedidos
    public static String[] classificacao = {"Diet", "Equilibrada", "Light", "Low carb",  "Low fat", "Natural", "Sem glúten", "Vegano", "Vegetariano"};

    /**** Metodos set e get ****/

    //descricao
    public void setDescricao(String descricao){

        this.descricao = descricao;
    }//end method setDescricao

    public String getDescricao(){

        return this.descricao;
    }//end method getDescricao

    //caloria
    public void setCaloria(int caloria){

        this.caloria = caloria;
    }//end method setCaloria

    public int getCaloria(){

        return this.caloria;
    }//end method getCaloria

    //custo
    public void setCusto(double custo){

        this.custo = custo;
    }//end method setCaloria

    public double getCusto(){

        return this.custo;
    }//end method getCaloria

    //tipoDeRefeicao
    public void setTipoDeRefeicao(int tipoDeRefeicao){

        this.tipoDeRefeicao = tipoDeRefeicao;
    }//end method setTipoDeRefeicao

    public String getTipoDeRefeicao(){

        return classificacao[(tipoDeRefeicao-1)];
    }//end method getTipoDeRefeicao

}

classe Cardapio:
package projeto_4;

import java.util.Scanner;

public class Cardapio {

    private Refeicao[][] menu;

    public Cardapio(){

      this.menu = new Refeicao[6][7];

    }//end contructor

    public void incluirRefeicao(){

        Scanner input = new Scanner(System.in);

        int i, j;

        for(i = 0; i < 6 ; i++)
        {
            for(j = 0; j < 7; j++)
            {

            System.out.printf("Digite a descrição da refeição: ");
            String strReceber = input.nextLine();
            menu[i][j].setDescricao(strReceber);

            System.out.printf("Digite a caloria: ");
            int intReceber = input.nextInt();
            menu[i][j].setCaloria(intReceber);

            System.out.printf("Digite o Custo: ");
            double floatReceber = input.nextDouble();
            menu[i][j].setCusto(floatReceber);

            System.out.printf("Digite o Tipo de refeição: ");
            intReceber = input.nextInt();
            menu[i][j].setTipoDeRefeicao(intReceber);

            }//end for(j = 0; j < 7; j++)

        }//end for(i = 0; i < 6 ; i++)

    }//end method incluirRefeicao

    public void listarMenu(){

        Scanner input = new Scanner(System.in);

        int i, j;

        for(i = 0; i < 6 ; i++)
        {
            for(j = 0; j < 7; j++)
            {

            System.out.printf("Digite a descrição da refeição: %s",
                    menu[i][j].getDescricao() );

            System.out.printf("Digite a caloria: %d",
                    menu[i][j].getCaloria() );

            System.out.printf("Digite o Custo: %.02f",
                    menu[i][j].getCusto() );

            System.out.printf("Digite o Tipo de refeição: %s",
                    menu[i][j].getTipoDeRefeicao() );

            }//end for(j = 0; j < 7; j++)

        }//end for(i = 0; i < 6 ; i++)

    }//end method listarMenu

    //linha][coluna

    public void alteraRefeicao(int linha, int coluna){

        Scanner input = new Scanner(System.in);

        System.out.printf("Digite a descrição da refeição: ");
            String strReceber = input.nextLine();
            menu[linha][coluna].setDescricao(strReceber);

            System.out.printf("Digite a caloria: ");
            int intReceber = input.nextInt();
            menu[linha][coluna].setCaloria(intReceber);

            System.out.printf("Digite o Custo: ");
            double floatReceber = input.nextDouble();
            menu[linha][coluna].setCusto(floatReceber);

            System.out.printf("Digite o Tipo de refeição: ");
            intReceber = input.nextInt();
            menu[linha][coluna].setTipoDeRefeicao(intReceber);

    }//end alteraRefeicao

}//end class Cardapio

Erro:

Exception in thread "main" java.lang.NullPointerException
      at projeto_4.Cardapio.incluirRefeicao(Cardapio.java:28)
      at projeto_4.RestauranteTeste.main(RestauranteTeste.java:11)
  /home/aluno/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java returned: 1
  FALHA NA CONSTRUÇÃO (tempo total: 4 segundos)
Answer: Note que o seu array foi somente definido no trecho:
public Cardapio() {
    this.menu = new Refeicao[6][7];
}// end contructor

Porém, além disso, você ainda precisa inicializar as instâncias que irão ocupar essas posições. Um simples ajuste seria ajustar a sua classe para:
public class Cardapio {

private Refeicao[][] menu;
public Cardapio() {
    this.menu = new Refeicao[6][7];
}// end contructor

public void incluirRefeicao() {
    Scanner input = new Scanner(System.in);
    int i, j;
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 7; j++) {
            if (Objects.isNull(menu[i][j])) // Verificar se esta posição ainda não tem um objeto instanciado
                menu[i][j] = new Refeicao(); // Caso não exista, instancia uma nova referência
            System.out.printf("Digite a descrição da refeição: ");
            String strReceber = input.nextLine();
            menu[i][j].setDescricao(strReceber);

            System.out.printf("Digite a caloria: ");
            int intReceber = input.nextInt();
            menu[i][j].setCaloria(intReceber);

            System.out.printf("Digite o Custo: ");
            double floatReceber = input.nextDouble();
            menu[i][j].setCusto(floatReceber);

            System.out.printf("Digite o Tipo de refeição: ");
            intReceber = input.nextInt();
            menu[i][j].setTipoDeRefeicao(intReceber);
        } // end for(j = 0; j < 7; j++)
    } // end for(i = 0; i < 6 ; i++)
}// end method incluirRefeicao

public void listarMenu() {
    Scanner input = new Scanner(System.in);
    int i, j;
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 7; j++) {
            System.out.printf("Digite a descrição da refeição: %s", menu[i][j].getDescricao());
            System.out.printf("Digite a caloria: %d", menu[i][j].getCaloria());
            System.out.printf("Digite o Custo: %.02f", menu[i][j].getCusto());
            System.out.printf("Digite o Tipo de refeição: %s", menu[i][j].getTipoDeRefeicao());
        } // end for(j = 0; j < 7; j++)
    } // end for(i = 0; i < 6 ; i++)
}// end method listarMenu

// linha][coluna

public void alteraRefeicao(int linha, int coluna) {
    Scanner input = new Scanner(System.in);
    System.out.printf("Digite a descrição da refeição: ");
    String strReceber = input.nextLine();
    menu[linha][coluna].setDescricao(strReceber);

    System.out.printf("Digite a caloria: ");
    int intReceber = input.nextInt();
    menu[linha][coluna].setCaloria(intReceber);

    System.out.printf("Digite o Custo: ");
    double floatReceber = input.nextDouble();
    menu[linha][coluna].setCusto(floatReceber);

    System.out.printf("Digite o Tipo de refeição: ");
    intReceber = input.nextInt();
    menu[linha][coluna].setTipoDeRefeicao(intReceber);
}// end alteraRefeicao
}// end class Cardapio

Comment: Olá. Implementei com a ideia do @Sósthenes Neto. Mas mesmo assim obrigado. Não da pra marcar sua resposta como relevante pq não tenho reputação suficiente pra fazer isso ainda :(  Depois vou tentar usar o 'if (Objects.isNull(menu[i][j]))' pq achei legal.
Comment: @ThiagoSoaresMota Você pode votar +1 em todas as respostas que achar úteis.
Answer: Tem que inicializar o elementos do seu array
Exemplo:
class Elemento {
    private String atributo;
    public void setAtributo(String atributo) {
        this.atributo = atributo;
    }
    public String getAtributo() {
        return atributo;
    }
}

class Elementos {
    private Elemento[][] elementos;

    public Elementos () {
        elementos = new Elemento[6][7];

        int i, j;
        for(i = 0; i < 6 ; i++) {

            System.out.println(elementos[i]);
            for(j = 0; j < 7; j++) {
                if (elementos[i][j] == null) {
                    elementos[i][j] = new Elemento();
                }
                elementos[i][j].setAtributo(String.format("Elemento [%d][%d]", i, j));
                System.out.println(elementos[i][j].getAtributo());
            }
        }
    }
}

class Teste {

    public static void main (String[] args) {
        System.out.println("inicio");
        for (String arg : args) {
            System.out.println(String.format("arg: '%s'", arg));
        }

        Elementos Elementos = new Elementos();
    }
}

Comment: Obrigado. Implementei usando seu exemplo como base.

Erro NullPointerException na execução


Youngest goal keepers in the World Cup

Question: Francis Uzoho Nigeria's goalie in the 2018 World Cup was only 19 years of age. While it is not uncommon to see teenagers in the World Cup in general, it is uncommon to see goalies starting for their national team in that age.
What are the top 5 youngest goaltenders to start a game in the world cup? Please provide the year and host, as well as the the teams in play in the games.
Answer: This is based on FIFA World Cup squads as listed on Wikipedia. (So it also depends on the accuracy of the data on Wikipedia.) In connection with this, I should mention that for some players age and birth date is completely missing or only year is shown. (This is mainly the case for earlier World Cups. Since sixties, these data seem to be more-or-less complete.)
Since the question explicitly asks about goalkeepers who started in a game, goalkeepers who were listed in a World Cup squad but stayed on a bench are not included. (Several younger players can be found if we drop this requirement.)
Men
Aged 19
The goalkeppers which played at World Cup at age 19.

Mustafa Mansour played for Egypt at 1934 FIFA World Cup in their only game against Hungary. He was 19 years old (born 2 August 1914).MM
Lee Chang-myung played for North Korea at 1966 FIFA World Cup. He played in all three matches in group stage (Soviet Union, Chile, Italy) and also in quarterfinals where North Korea was eliminated by Portugal. He was 19 years old (born 2 January 1947).
Vincent Enyeama played for Nigeria at 2002 FIFA World Cup. It was at age 19 (born 29 August 1982). He played in the last match in group stage against England.
Francis Uzoho played for Nigeria at 2018 FIFA World Cup. He played in all three matches in the groups stage (Croatia, Iceland, Argentina). He was 19 at the time (born 28 October 1998).

Women
An answer that was already posted covers goalkeepers at FIFA Women's World Cup. Here is some additional information.

Cecilia Santiago played for Mexico at 2011 World Cup. She played in all three matches in the group stage (England, Japan, New Zealand). She was 16 at the time (born 19 October 1994).
Ann Chiejine played for Nigeria at 1991 World Cup. She played in all matches in group stage (Germany, Italy, Chinese Taipei). This was at age 17 (born 2 February 1974).
Lin Hui-fang played for Chinese Taipei at 1991 World Cup. She played in two matches in group stage - against Germany and Nigeria. She was 18 years old (born 6 October 1973).
Linnea Quinones played for Mexico at 1999 FIFA Women's World Cup. She played in all three matches in the group stage (Brazil, Germany, Italy).
At the age of 18 (born 17 July 1980).
Kim Jung-mi played for South Korea at 2003 FIFA World Cup. She played in all three matches in the group stage (Brazil, France and Noway). She was 18 at the time (born 16 October 1984).

Sources

As mentioned above, this is based on FIFA World Cup squad list on Wikipedia.
The article 2018 world Cup: Nigerian Prodigy (Internet Archive) about Frances Uzoho lists youngest goalkeeper for each individual World Cup.
1934: The flying Egyptian (Internet Archive) - an article about Mustafa Kamel Mansour.
Mis mundiales by Juan María Alfaro contains a list of youngest and oldest goalkeepers.

MMReport on the FIFA website (Internet Archive) lists Kamel Masoud as a goalkeeper - which is most likely a mistake since he was a forward. But based on other sources, it seems that Mustafa Mansour indeed played in this match. (Although the article about Uzozo also lists Masoud and in Mis Mundiales Mansour is listed as 20 years old.)
Answer: Your question is somewhat ambiguous.  Not counting youth tournaments such as the U-17 and U-20 World Cups, the youngest goalkeeper ever to start in a World Cup was Cecilia Santiago of Mexico, born 19 October 1994, in a 1–1 draw vs. England on 27 June 2011.  She was 16 years and 251 days old.
At least one fifteen-year-old goalkeeper has sat on the bench in a World Cup, Yun Hyon-hi of North Korea in 2007.  In fact, she was still a teenager when she got her first World Cup start in 2011.
Although I don't have a complete ranking by age in days, the rest of the top five are also women, or girls at the time.  There are several teenage goalkeepers at every Women's World Cup (the first being Ann Chiejine, who was 17 when she played for Nigeria versus Germany on November 17, 1991), while there are no goalkeepers in FIFA's official list of the youngest men to ever play in a World Cup, which stops at 19 years, 4 months, and 21 days.
Answer: Luis Ricardo Guevara Mora (Born 2 september 1962? 1964?); goalkeeper of El Salvador in Spain'82 could be at least one of youngest goalkeeper in world cup history. Some Salvadoran journalists say that he was 18 years old when he played the world cup, it is the age that appears on the official world cup album (although FIFA reports that he was 20), He would have lied his age to the authorities of the Federation to be able to collect the travel expenses for his participation in the World Cup.

Youngest goal keepers in the World Cup


Migração de banco de dados de um servidor para outro

Question: Tenho um E-Commerce que desenvolvi através do Wordpress, todo o BD dele estava no meu antigo servidor, com a URL http://www.felipestoker.com/teste
Agora, já finalizado, tenho que exportar tudo para http://www.teste.com.br
Já exportei os arquivos, instalei o Banco de dados no novo servidor, porém estou tendo problema com os nomes de URLs, pois ainda está informado o antigo. Como modificar manualmente?
Answer: Na verdade todo o procedimento de migração do Wordpress deve ser minunciosamente pré-meditado para que não tenha problemas tão grande quanto o tamanho do sistema em questão.
Vou mostrar um passo do que deve ser feito e te recomendo começar tudo de novo conforme passo a passo demonstrado apagando todo procedimento feito até agora e começando outra vez para ter certeza de que vai ficar tudo bem.

Assim que tiver finalizado seu sistema zip a pasta da raiz ...
Exporte o arquivo zip até o destino final e unzip o arquivo ...
Acesse o wp-config.php e coloque as novas informações do bando de dados ...
Exporte a DB em .sql ou .tar.gz ou qualquer extensão suportada pela importação ...
Importe esta DB para seu banco novo e vá na tabela wp-options ...
Nesta tabela, vai modificar a coluna option_name=>siteurl ...
Em option_name=>siteurl coloque a url do domínio definitivo ...

Após ter feito todos estes passos, você deverá acessar dominiodefinitivo.com.br/wp-admin e entrar o nome de usuário e senha na tela de login e assim que abrir a área administrativa deverá imediatamente ir para Configurações => Geral e modificar as url's conforme mostrada na imagem abaixo:

Se desenvolveu o site sem mexer nas estruturas do CMS e sem ter inserido links manuais no theme, ao acessar seu domínio definitivo tudo estará ok.
Espero ter ajudado.
Comment: Excelente reposta, atualizei minha pergunta. Estou com erro nas páginas internas agora.
Comment: Só se eu alterar do "com www" para "sem www".
Comment: Pode tentar mas acho que isso ainda não é a origem do problema. Tenta apagar tudo no domínio definitivo e começar segundo o passo a passo.
Comment: Descobri o problema. Era com os links permanentes. Resolvi com esse plugin https://wordpress.org/plugins/rewrite-flush-button/
Comment: Você está com problema sério na importação porque `http://www.encamisetados.com.br/` náo vai pro mesmo lugar que `http://encamisetados.com.br/` ... aguardo sua interação.
Comment: Creio que não é esse o problema, atualizei a minha pergunta, com uma imagem no final de como está.


C# app with a built-in FTP Server

Question: At my work I am writing a C# app, which among its direct functionality should allow user to turn their computer into an FTP server.
Probably it would be more practical to use FileZilla Server, but the I have to aim at really amateur users who are not able to configure FileZilla Server and would like to start an FTP from my soft with one button click.
At the moment I really have no idea, where to start from and asking for some advice.
Comment: [Google](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=c%23%20ftp%20server) is a good place to start, but this format of question isn't a good fit for this site. Do some research, type some code, StackOverflow when the code doesn't work and we can help at that point.
Answer: You need to look towards a win32 app published in the Windows Store. The API of apps won't give you enough priviledge for this.

C# app with a built-in FTP Server


Help with wedge product proof?

Question: I am an undergraduate physics student trying to learn this on my own, so it's been a bear digging through either very general resources or resources that don't answer my questions.
What I am trying to prove is:
$$a \wedge b = (e_{x} \wedge e_{y} \wedge e_{z}) \cdot (a \times b)$$
...by direct computation in components and term identification where $$e_{i}$$ is a basis vector and $$a,b$$ are unit vectors in some arbitrary direction (describing a detector direction chosen experimentally).
My understanding is that it should look something like this:
$$(e_{x} \wedge e_{y} \wedge e_{z}) \cdot ((a_{2}b_{3}-a_{3}b_{2})e_{x} + (a_{1}b_{3}-a_{3}b_{1})e_{x}) + (a_{1}b_{2}-a_{2}b_{1})e_{x})$$
But I don't know how to actually go through the steps to get there since I have never even taken abstract algebra.
Comment: @MattS I updated it
Comment: To use mathjax, just put a dollar sign either side of your equation (\$). So to type "$\wedge$", you do "\$\wedge\$".
Comment: What have you got so far?
Comment: what properties of the wedge do you know of
Comment: You mentioned both Clifford algebra and exterior algebra, but the wedge product is different between the two in general. Which one do you mean?
Answer: Let $uv$ represent the Clifford product of multivectors $u$ and $v$.  I will also assume that $e_x, e_y, e_z$ is an orthonormal basis with respect to the usual inner product on $\Bbb R^3$.  This implies that $e_i\wedge e_j = e_ie_j$ for all $i \ne j$.  Then
\begin{align}&(e_{x} \wedge e_{y} \wedge e_{z}) \cdot \big[(a_{2}b_{3}-a_{3}b_{2})e_{x} + (a_{3}b_{1}-a_{1}b_{3})e_{y} + (a_{1}b_{2}-a_{2}b_{1})e_{z}\big] \\
&= (e_xe_ye_z)\cdot \big[(a_{2}b_{3}-a_{3}b_{2})e_{x} + (a_{3}b_{1}-a_{1}b_{3})e_{y} + (a_{1}b_{2}-a_{2}b_{1})e_{z}\big] \\
&= (a_2b_3-a_3b_2)\big[(e_xe_ye_z)\cdot e_x\big] + (a_3b_1-a_1b_3)\big[(e_xe_ye_z)\cdot e_y\big] + (a_1b_2-a_2b_1)\big[(e_xe_ye_z)\cdot e_z\big] \\
&= (a_2b_3-a_3b_2)\langle (e_xe_ye_z)e_x\rangle_2 + (a_3b_1-a_1b_3)\langle (e_xe_ye_z)e_y\rangle_2 + (a_1b_2-a_2b_1)\langle(e_xe_ye_z)e_z\rangle_2 \\
&= (a_2b_3-a_3b_2)\langle e_xe_xe_ye_z\rangle_2 + (a_3b_1-a_1b_3)\langle -e_xe_ye_ye_z\rangle_2 + (a_1b_2-a_2b_1)\langle e_xe_ye_ze_z\rangle_2 \\
&= (a_2b_3-a_3b_2)e_ye_z - (a_3b_1-a_1b_3) e_xe_z + (a_1b_2-a_2b_1)e_xe_y \\
&= (a_2b_3-a_3b_2)e_y\wedge e_z + (a_3b_1-a_1b_3) e_z\wedge e_x + (a_1b_2-a_2b_1)e_x\wedge e_y \\
&= a\wedge b\end{align}

Help with wedge product proof?


Can you help me analyze I-bVII-IV6-III?

Question: Playing around today I really liked the sound of C-Bb-F6-E as a four chord loop and I really don't understand why. Maybe calling the third chord Dm7/F makes more sense? I think each transition is smooth and easy to voice lead but I can't make sense of it otherwise. Am I missing something obvious in analysis? Can someone make more sense of this than I could?
Comment: Sometimes voice-leading trumps (straightforward) harmonic analysis... :)
Comment: Dm/F doesn't have a C in it. F6 does. Dm7/F and F6 each contain the same four pitches. Which are you referring to?
Comment: Also, your post suggests all of the chords are voiced in root position. If that's the case, please confirm; if not, please indicate the notes played in each chord from lowest to highest.
Comment: Good catch, Aaron, thanks. Edited to correct to Dm7/F. All chords are voiced in root position (unless we're calling it Dm7/F rather than F6, in which case it's in first inversion, I guess).
Comment: That helps. Thanks. And you experience the Bb to F6 transition as smooth?
Comment: Yes, although checking again both with and without the C in the third chord I do think it's smoother without the C
Answer: C-Bb-F6 is a I-bVII-IV(-I) progression in C mixolydian (the 5th mode of major) a popular rock progression. As a logical consequence, Dm7/F doesn't seem like the correct spelling, especially since the D in F6 sounds more like a decoration/extension, likely because bVII-IV-I is a pattern of falling fourths.
I suppose E is taking the function of V/VIm (the dominant chord of VIm), but instead of resolving to VIm (Am), it resolves to its relative major, I (C), which turns out to work very pleasantly: the fifth of E (B) resolves up a semitone to the root of C (C), and the third of E (G#) resolves down a semitone to the fifth of C (G), thus giving E its dominant function due to the instability of the chord followed by a well-defined tonic.
Comment: A nice analysis, but I disagree technically about mixolydian. In jazz, blues, rock, and pop, pieces that use the b7 are still considered major.
Comment: I agree with @Aaron, not Mixolydian but major and the Bb is more of a borrowed chord from the parallel minor. A couple of indicators are pop melodies are more likely to use the ^M7 than the ^m7. Also pop tunes almost always use a iii not a iiio in their harmony. Otherwise, nice job, +1.

Can you help me analyze I-bVII-IV6-III?


How to get reducer output as a xml format in hadoop

Question: I created a custom xmloutputformat class that translate  reducer's output into xml format.
The Problem here is the code executes successfully but the final output is in normal format instead of XML format.
Can anyone please help me out..?
package dd;

import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class MaxTemperature extends Configured implements Tool {

public static class MapMapper extends
        Mapper<LongWritable, Text, Text, IntWritable> {
    private static final int MISSING = 9999;

    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {

        String line = value.toString();
        String year = line.substring(15, 19);
        int airTemperature;
        if (line.charAt(87) == '+') { // parseInt doesn't like leading plus
                                        // signs
            airTemperature = Integer.parseInt(line.substring(88, 92));
        } else {
            airTemperature = Integer.parseInt(line.substring(87, 92));
        }
        String quality = line.substring(92, 93);
        if (airTemperature != MISSING && quality.matches("[01459]")) {
            context.write(new Text(year), new IntWritable(airTemperature));
        }

    }

}

public static class Mapreducers extends
        Reducer<Text, IntWritable, Text, IntWritable> {

    public void reduce(Text key, Iterable<IntWritable> values,
            Context context) throws IOException, InterruptedException {

        int maxValue = Integer.MIN_VALUE;
        for (IntWritable value : values) {
            maxValue = Math.max(maxValue, value.get());
        }

        context.write(key, new IntWritable(maxValue));

    }

}

public int run(String[] args) throws Exception {
    Job job = new Job();
    job.setJarByClass(MaxTemperature.class);
    job.setJobName("MaxTemperature");

    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(URI.create(args[0]), conf);

    if (fs.exists(new Path(args[1]))) {
        fs.delete(new Path(args[1]), true);
    }

    FileInputFormat.addInputPath(job, new Path(args[0]));
    XmlOutputFormat.setOutputPath(job, new Path(args[1]));

    job.setMapperClass(MapMapper.class);
    job.setCombinerClass(Mapreducers.class);
    job.setReducerClass(Mapreducers.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    return job.waitForCompletion(true) ? 0 : 1;
}

public static void main(String[] args) throws Exception {
    int xx = 1;
    xx = ToolRunner.run(new MaxTemperature(), args);
    System.exit(xx);
}

 }

The custom xmlformat code is shown below:-
package dd;

import java.io.DataOutputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataOutputStream;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

 /** An {@link OutputFormat} that writes plain text files. */
public class XmlOutputFormat<K, V> extends FileOutputFormat {
protected static class XmlRecordWriter<K, V> extends RecordWriter<K, V> {
    private static final String utf8 = "UTF-8";
    protected DataOutputStream out;

    public XmlRecordWriter(DataOutputStream out) throws IOException {
        this.out = out;
        out.writeBytes("<results>\n");
    }

    /**
     * Write the object to the byte stream, handling Text as a special case.
     *
     * @param o
     *            the object to print
     * @throws IOException
     *             if the write throws, we pass it on
     */
    private void writeObject(Object o) throws IOException {
        if (o instanceof Text) {
            Text to = (Text) o;
            out.write(to.getBytes(), 0, to.getLength());
        } else {
            out.write(o.toString().getBytes(utf8));
        }
    }

    private void writeKey(Object o, boolean closing) throws IOException {
        out.writeBytes("<");
        if (closing) {
            out.writeBytes("/");
        }
        writeObject(o);
        out.writeBytes(">");
        if (closing) {
            out.writeBytes("\n");
        }
    }

    public synchronized void write(K key, V value) throws IOException {

        boolean nullKey = key == null || key instanceof NullWritable;
        boolean nullValue = value == null || value instanceof NullWritable;
        if (nullKey && nullValue) {
            return;
        }
        Object keyObj = key;

        if (!nullKey) {
            keyObj = "value";
        }

        writeKey(keyObj, false);
        if (!nullValue) {
            writeObject(value);
        }
        writeKey(keyObj, true);
    }

    public synchronized void close(TaskAttemptContext context)
            throws IOException {
        out.close();
    }
}

public RecordWriter<K, V> getRecordWriter(TaskAttemptContext job)
        throws IOException, InterruptedException {
    Path file = FileOutputFormat.getOutputPath(job);
    Configuration conf = new Configuration();
    FileSystem fs = file.getFileSystem(conf);

    FSDataOutputStream fileout = fs.create(file);
    return new XmlRecordWriter<K, V>(fileout);

}

}

--
Thanks in advance.
Comment: while debugging i came to know that the complete XmlOutputFormat class not populating.is it right way that i invoke the xmlOutputFormat in run method ?
Answer: Hope this helps you.
You can go through this and modify your code accordingly.
Link
UPDATE
@Override
protected void setup(Context context)
      throws IOException, InterruptedException {
    context.write(new Text("<MapReduce>"), null);
  }

public static class Mapreducers extends
        Reducer<Text, IntWritable, Text, IntWritable> {

    public void reduce(Text key, Iterable<IntWritable> values,
            Context context) throws IOException, InterruptedException {
int maxValue = Integer.MIN_VALUE;
for (IntWritable value : values) {
     maxValue = Math.max(maxValue, value.get());
}
Text out = new Text(constructPropertyXml(key, maxValue));
context.write(out, null);
  }

}
public static String constructPropertyXml(Text key, Text maxvalue) {
    StringBuilder sb = new StringBuilder();
    sb.append("<result><key>").append(key)
        .append("</key><value>").append(maxvalue)
        .append("</value></result>");
    return sb.toString();
  }
@Override
  protected void cleanup(Context context)
      throws IOException, InterruptedException {
    context.write(new Text("</MapReduce>"), null);
  }

Comment: in the given link input to the map reduce job also xml but i need only output should be xml and the input is normal key value pair.. let me know if i am wrong..
Comment: current output : 1949 21 1950 11 expected output: 1949>21195011
Comment: Yes you can do with the same: ok can u show me ur current o/p and expected o/p?
Answer: Simply you can override your RecordWriter like this. You can change the root tag, parent tag and the child tag names.
protected static class XMLRecordWriter extends RecordWriter<Text, IntWritable> {

private DataOutputStream out;

public XMLRecordWriter(DataOutputStream out) throws IOException
{

this.out = out;

out.writeBytes("<Output>\n");

}

private void writeStyle(String xml_tag,String tag_value) throws IOException{

out.writeBytes("<"+xml_tag+">"+tag_value+"</"+xml_tag+">\n");

}

public synchronized void write(Text key, IntWritable value) throws IOException

{

out.writeBytes("<record>\n");

this.writeStyle("key", key.toString());

this.writeStyle("value", value.toString());

out.writeBytes("</record>\n");

}

public synchronized void close(TaskAttemptContext job) throws IOException

{

try {

out.writeBytes("</Output>\n");

} finally {

out.close();

}

}
}

You can also refer to the below link for more details on implementing custom output format in Hadoop.
https://acadgild.com/blog/implementing-custom-output-format-hadoop/


Load and run test a .trt model

Question: I need to run my model in NVIDIA JETSON T2, So I converted my working yoloV3 model into tensorRT(.trt format)(https://towardsdatascience.com/have-you-optimized-your-deep-learning-model-before-deployment-cdc3aa7f413d)This link mentioned helped me to convert the Yolo model into .trt .But after converting the model to .trt model I needed to test if it works fine (i.e) If the detection is good enough. I couldn't find any sample code for loading and testing .trt model. If anybody can help me , please pull up a sample code in the answer section or any link for reference.
Comment: Please share your tensorrt version.
Comment: Tensorrt 5.0 ......
Comment: Officiel nvidia tutorial for inference in python using `.trt`: https://github.com/NVIDIA/TensorRT/blob/main/quickstart/SemanticSegmentation/tutorial-runtime.ipynb
Answer: You can load and perform the inference of your TRT Model using this snippet of code.
This is executed in Tensorflow 2.1.0 and Google Colab Environment.
from tensorflow.python.compiler.tensorrt import trt_convert as trt
from tensorflow.python.saved_model import tag_constants

saved_model_loaded = tf.saved_model.load(output_saved_model_dir, tags=[tag_constants.SERVING])
signature_keys = list(saved_model_loaded.signatures.keys())
print(signature_keys) # Outputs : ['serving_default']

graph_func = saved_model_loaded.signatures[signature_keys[0]]
graph_func(x_test) # Use this to perform inference

output_saved_model_dir is the location of your TensorRT Optimized model in SavedModel format.
From here, you can add your testing methods to determine the performance of your pre and post-processed model.
EDIT:
import tensorflow as tf
from tensorflow.python.compiler.tensorrt import trt_convert as trt
import numpy as np

conversion_params = trt.DEFAULT_TRT_CONVERSION_PARAMS
conversion_params = conversion_params._replace(max_workspace_size_bytes=(1<<32))
conversion_params = conversion_params._replace(precision_mode="FP16")
conversion_params = conversion_params._replace(maximum_cached_engines=100)

converter = trt.TrtGraphConverterV2(
    input_saved_model_dir=input_saved_model_dir,
    conversion_params=conversion_params)

converter.convert()

converter.save(output_saved_model_dir)

Here are the codes used for Converting and Saving the Tensorflow RT Optimized model.
Comment: Hi @SaiKrishnadas, Yes. the TRT Engine as you mentioned is saved along with the normal nodes in the SavedModel file. As you can see the code snippet, the way that it is used for inference is different to the normal ```predict(x_test)```, this already uses the signatures saved with the model.
Comment: Hi @SaiKrishnadas, in Tensorflow 2 you can only use the SavedModel format for inference, because converting the frozen graphs are not supported in TF2.0. I have editted my answer.
Comment: Hi @SaiKrishnadas, I only included the TrtGraphConverterV2 to show how I created and converted the optimized model. The only thing you need to load your converted model is the first code I included. Then after that you can do anything you want on the model and the rest of the codes.
Comment: Thanks for the response. But does tf.saved_model load .trt engine ?
Comment: So In case im using it for object recogination. Is it okay to write a detection script with tensorflow and load this .trt model ?
Comment: Hi @SaiKrishnadas, you really need to write it first using Tensorflow, then convert/optimize it using Tensorflow RT. This approach applies to all not only for Object recognition.
Comment: I dint ask about the weight file.
Comment: Thanks,  But I have managed to convert it to onnx then to tensorrt (.trt format ) as I'm using YoloV3 which was originally written in C++. As of now, I have a optimizied .trt model. So, Why does the trt.TrtGraphConverterV2 is called again ?
Comment: Hi @SaiKrishnadas, this is all based on NVIDIA's documentation about Tensorflow TensorRT. trt.TrtGraphConverterV2 is used to convert the graph of the model, resulting into a optimized one. ```V2``` means that it is for Tensorflow 2. Also I am discussing here based on Python language as discussed in the documentation in this [link](https://docs.nvidia.com/deeplearning/frameworks/tf-trt-user-guide/index.html).
Comment: Yeah , As you said it converts Tensorflow model to an optimized Tensorrt model. But that isn't required for me as I have already converted it into Tensorrt through onnx. So, my question was why should I use trt.TrtGraphConverterV2 again
Comment: Okay, Thanks... I will close this question once I work with them
Comment: Sure thing @SaiKrishnadas, Glad to help. Thanks.

Load and run test a .trt model


Show the Quantity field on the product page but hide it on the catalog page

Question: I created an "ABC Book" product, whose URL is https://example.com/product/1. I added the Quantity field from Administration > Commerce > Configuration > Order item types > Default > Manage form display > Add to cart.
The field appears on the product details page (https://example.com/product/1).
I created a view to display all products on a page (https://example.com/shop). The field also appears on the view.
How can I hide the field on https://example.com/shop, but still show it on https://example.com/product/1?
Answer: You may find the views documentation useful
If I understand your question correctly, you may either set, for you view:

a different display under the view setting format, content and then set up the right fields you want to show on the product display configuration
On the view settings, again under the format sections use the fields settings, and then directly select the fields you want do display in the view
Comment: There is no specific field for quantity.

I have created a view mode for products, let's say its name is "teaser". I am using this teaser mode to display in the view (shop). But there is no quantity field to control its visibility.


What is the distribution of changes in adjusted R squared when adding a random normal variable?

Question: Suppose we have a model with $n$ data points and $p$ predictors.  The model has an $R^2_{\text{adjusted}}=q$.
What sort of distribution does the change in $R^2_{\text{adjusted}}$ have when a random Gaussian predictor is added to the model?
I am assuming that the expected value is zero, since $R^2_{\text{adjusted}}$ is supposed to adjust for predictors that have no explanatory power.  But I can't find the answer anywhere, and I'm having trouble working it out myself.
...
Comment: [Wikipedia](http://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2) confirms your supposition that the expectation will be zero. The distribution, as a linear transformation of a ratio of sums of squares, tends to be strongly skewed. You might consider beginning with the case of *no* predictors (except a constant) and consider what happens when you include one independent predictor.
Answer: Here's a quick  simulation in R that gives you a feel for the distribution of $R^2_{adj}$ when adding a single random normal variable.
<code>set.seed(1234)
adj_r_simulation <- function(n=100) {
    y <- rnorm(n)
    x <- rnorm(n)
    fit <- lm(y~x)
    summary(fit)$adj.r.squared
}

# Simulate adjusted r-square values
simulations <- 1000
n <- 100
x <- sapply(seq(simulations), function(X) adj_r_simulation(n=n))

# Display results
mean(x)
sd(x)
plot(density(x),
     main=paste0("n=",n, "; simulations=", simulations),
     xlab='Adjusted r-squared')
abline(v=mean(x))
</code>
The simulation above simulates two independent normal variables, x and y of sample size n=100. It then fits a linear model predicting y from x and returns $R^2_{adj}$. This process is repeated 1000 times and the values are saved. The sample mean of simulated $R^2_{adj}$ values is close to zero:
<code>> mean(x)
[1] 0.0002181863
> sd(x)
[1] 0.01425647
</code>
Below you can see the density plot of the simulated values of $R^2_{adj}$. This illustrates whuber's point about the distribution being highly skewed.


Absolute value of functions in Sobolev space

Question: I'm just trying to show that if $u\in W^{1,p}(U)$ (with $1\leq p<\infty$) then $|u|\in W^{1,p}(U)$. Here $U$ is bounded.
I originally took smooth functions $a_n$, equal to $|x|$ whenever $|x|\geq 1/n$ and which converged uniformly to $|x|$; this implies that $a_n(u)$ is Cauchy in $L^p$, so all I needed to do was show that $Da_n(u)$ was Cauchy, but then I ran into problems.
Namely, since no smooth functions approach the sign function uniformly, I can't seem to bound $||D_{x_i}(a_n(u)-a_m(u))||=||(a_n'(u)-a_m'(u))u_{x_i}||$.
Anyone know a way around this, or an easier approach? (If you're going to quote mollifiers, please be specific because I feel I've exhausted all approaches that use them!)
Comment: I've just realized since $U$ is bdd, constant functions are L^p, so the DCT may be an option.
Answer: A characterization of $W^{1,p}(U)$ is that $u\in W^{1,p}(U)$ if and only if $u$ is absolutely continuous in almost every horizontal and almost every vertical line, and the partial derivatives are in $L^p(U)$.
We assume that $u\in W^{1,p}(U)$. Note that $\left|\frac{|u(x+he_i)|-|u(x)|}{h}\right| \leq \frac{|u(x+he_i)-u(x)|}{|h|}$
so if the partial derivatives of $|u|$ exist, they will also lie in $L^p(U)$.
Furthermore, note that for almost every horizontal or vertical line $\gamma$ and for all points $x,y\in \gamma$ we have
$$||u(x)|- |u(y)|| \leq |u(x)-u(y)| = \left| \int_{\gamma|_{[x,y]}} \nabla u ds \right|  \leq \int_{\gamma |_{[x,y]}} |\nabla u| ds$$
where $\gamma|_{[x,y]}$ is the subsegment of $\gamma$ from $x$ to $y$.
The above inequality shows that $|u|$ is absolutely continuous in almost every horizontal and almost every vertical line, and in particular the partial derivatives exist, as desired.
Answer: You don't need $a_n'$ to converge uniformly to the sign function; it's enough to have them uniformly bounded and converging pointwise.   (If your chosen $a_n$ functions don't do this, then pick other ones that do.)  Then you can use the dominated convergence theorem to show that $a_n'(u) u_{x_i} \to \operatorname{sgn}(u) u_{x_i}$ in $L^p$.
Comment: Lol just realized before you posted. Thanks for a more complete answer though.


Given a known isosceles Trapezoid find height of another with same angles & one base but different area

Question: I have a problem involving isosceles trapezoids. I have a shape as in the picture with all dimensions known in black or I have the ability to calculate the rest of the black ones as there are enough known.
The problem is I need a way to find out the height ($h_2$) of a trapezoid that is similar given side $b$ and the angles will stay the same, but the only other unit I know is the area ($Y$) of the similar shape.
So the question is can the height ($h_2$) be obtained from the original, given the area ($Y$) of the new trapezoid?
Any help or hints appreciated as this problem is driving me mad.
Comment: Do you know $a_2$?. It's not clear how new trapezoid is formed. Does $a_2$ go thru the intersection of a diagonal and $DE$?
Comment: $${a_2\over a}={h_2\over h}=\sqrt{Y\over Z}.$$
Answer: The area of the smaller trapezoid $A_2=\frac{b+a_2}{2}h_2$, The area of the bigger trapezoid is $A_1=\frac{b+2}{2}h$. Thus, $A_1/A_2=\frac{(b+a)h}{(b+a_2)h_2}$. Thus, we can find $a_2h_2$. Also, from similar triangles $h_2/h=(a_2-b)/(a-b)$. Two variables and two equations, we should be able to solve them.
Answer: You have
$$\frac{b+a_2}{2}h_2=Y,$$
and
$$\frac{b+a_2}{2}h_2+\frac{a+a_2}{2}(h-h_2)=\frac{a+b}{2}h.$$
Solving these equations for $h_2$ results in
$$h_2 = \frac{-bh+\sqrt{b^2 h^2+2(a-b)Yh}}{a-b}.$$
Verification:
If $Y=0$ then $h_2 = 0$, and $Y=(a+b)h/2 \implies h_2=h$.


Are field extensions faithfully flat?

Question: Is $\mathbb{C}$ a faithfully flat $\mathbb{R}$-module? In the general case, is it true that if $k$ is a field and $K$ is it's algebraic closure then $K$ is a faithfully flat $k$-module?
Thank you for your time.
Comment: If $k$ is any field, then all $k$-modules are free, hence faithfully flat.
Answer: All extensions of fields are faithfully flat.
You can use the criterion that every prime ideal of the small field
is the inverse image of one in the large field.
Comment: Thank you both for your answers, where can I find these cretierion?
Comment: @matemagreek On  Wikipedia for a start. https://en.wikipedia.org/wiki/Flat_module

Are field extensions faithfully flat?


Erro de cast ao rodar o serviço rest

Question: Estou tendo esse erro:

The 'Qtde' property on 'ItensLib' could not be set to a
  'System.Double' value. You must set this property to a non-null value
  of type 'System.Single'.

O que pode causar isso?
[Table("ITENSLIB")]
    public class ItensLib
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column("ID_ITENSLIB")]
        public int IdItensLib { get; set; }
        [Column("ID_ORCAMENTO")]
        public int IdOrcamento { get; set; }
        [Column("ID_PRODUTO")]
        public int IdProduto { get; set; }
        [Column("PRODUTO")]
        public string Produto { get; set; }
        [Column("QTDE")]
        public float Qtde { get; set; }
        [Column("UNITARIO")]
        public float Unitario { get; set; }
        [Column("CUSTO")]
        public float Custo { get; set; }
        [Column("MINIMO")]
        public float Minimo { get; set; }
        [Column("TOTAL")]
        public float Total { get; set; }
        [Column("CUSTODIARIO")]
        public float CustoDiario { get; set; }
        [Column("FABRICANTE")]
        public string Fabricante { get; set; }
        [Column("ULT_CONDICAO")]
        public float UltCondicao { get; set; }
        [Column("PROGRAMA")]
        public string Programa { get; set; }
        [Column("NOME_PC")]
        public string NomePc { get; set; }
        [Column("NOME_PROCEDURE")]
        public string NomeProcedure { get; set; }
        [Column("Flag_Vencido")]
        public byte FlagVencido { get; set; }
        [Column("TipoVenda")]
        public string TipoVenda { get; set; }
        [Column("VENDA_VISTA")]
        public float VendaVista { get; set; }
        [Column("MARGEM_AVISTA")]
        public float MargemAvista { get; set; }
        [Column("QTDE_NEG_AVISTA")]
        public float QtdNegAvista { get; set; }
        [Column("VENDA_PRAZO")]
        public float VendaPrazo { get; set; }
        [Column("PM_PRAZO")]
        public float PmPrazo { get; set; }
        [Column("MARGEM_PRAZO")]
        public float MargemPrazo { get; set; }
        [Column("JUROS_PRAZO")]
        public float JurosPrazo { get; set; }
        [Column("QTDE_PRAZO")]
        public float QtdePrazo { get; set; }
        [Column("VENDA_VISTA_ANT")]
        public float VendaVistaAnt { get; set; }
        [Column("MARGEM_AVISTA_ANT")]
        public float MargemAvistaAnt { get; set; }
        [Column("QTDE_NEG_AVISTA_ANT")]
        public float QtdeNegAvistaAnt { get; set; }
        [Column("VENDA_PRAZO_ANT")]
        public float VendaPrazoAnt { get; set; }
        [Column("PM_PRAZO_ANT")]
        public float PmPrazoAnt { get; set; }
        [Column("MARGEM_PRAZO_ANT")]
        public float MargemPrazoAnt { get; set; }
        [Column("JUROS_PRAZO_ANT")]
        public float JurosPrazoAnt { get; set; }
        [Column("QTDE_PRAZO_ANT")]
        public float QtdePrazoAnt { get; set; }
        [Column("VENDA_VISTA_ANT1")]
        public float VendaVistaAnt1 { get; set; }
        [Column("MARGEM_AVISTA_ANT1")]
        public float MargemAvistaAnt1 { get; set; }
        [Column("QTDE_NEG_AVISTA_ANT1")]
        public float QtdeNegAvistaAnt1 { get; set; }
        [Column("VENDA_PRAZO_ANT1")]
        public float VendaPrazoAnt1 { get; set; }
        [Column("PM_PRAZO_ANT1")]
        public float PmPrazoAnt1 { get; set; }
        [Column("MARGEM_PRAZO_ANT1")]
        public float MargemPrazoAnt1 { get; set; }
        [Column("JUROS_PRAZO_ANT1")]
        public float JurosPrazoAnt1 { get; set; }
        [Column("QTDE_PRAZO_ANT1")]
        public float QtdePrazoAnt1 { get; set; }
    }

Essa é minha chamada
public class ItensLiberacao
    {
        AutorizadorContext contexto = new AutorizadorContext();
        ItensLibDTO libDTO = new ItensLibDTO();

        [Route("itens/{id}")]
        public ItensLibDTO getItensLib(int id)
        {
            var lista = contexto.ItensLibs
                .Where(itens => itens.IdOrcamento == id)
                .Select(item => new ItensLibDTO
                {
                    Produto = item.Produto,
                    Qtde = item.Qtde.ToString(),
                    Unitario = item.Unitario.ToString(),
                    Custo = item.Custo.ToString(),
                    CustoDiario = item.CustoDiario.ToString(),
                    UltCondicao = item.UltCondicao.ToString(),
                    Total = item.Total.ToString()
                }).FirstOrDefault();

            return lista;
        }
    }

Meu serviço
[RoutePrefix("api/itens")]
    public class ItensController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        ItensLiberacao itens = new ItensLiberacao();

        [AcceptVerbs("Get")]
        public HttpResponseMessage getItensLiberacao(int id)
        {
            var _itens = contexto.ItensLibs.Where(it => it.IdOrcamento == id).FirstOrDefault();
            return Request.CreateResponse(HttpStatusCode.OK, _itens);

        }
    }

Answer: Resolvi alterando o método. Não entendi, mas deu certo:
[Route("itens/{id}")]
        public List<ItensLibDTO> getItensLib(int id)
        {
            var lista = contexto.ItensLibs
                .Where(itens => itens.IdOrcamento == id)
                .Select(item => new ItensLibDTO
                {
                    Produto = item.Produto,
                    Qtde = item.Qtde.ToString(),
                    Unitario = item.Unitario.ToString(),
                    Custo = item.Custo.ToString(),
                    CustoDiario = item.CustoDiario.ToString(),
                    UltCondicao = item.UltCondicao.ToString(),
                    Total = item.Total.ToString()
                }).ToList();

            return lista;
        }

E claro a chamada
[AcceptVerbs("Get")]
        public IEnumerable<ItensLibDTO> getItensLiberacao(int id)
        {
            return itens.getItensLib(id).AsEnumerable().ToList();
        }

Answer: O problema esta aqui:
var _itens = contexto.ItensLibs.Where(it => it.IdOrcamento == id).FirstOrDefault();

Na hora de traduzir o SQL para C#, você esta atribuindo um valor null para a propriedade QTDE que não aceita esse valor.
[Column("QTDE")]
public float Qtde { get; set; }

Faça esse ser um Nullable<float> que vai funcionar.
[Column("QTDE")]
public float? Qtde { get; set; }

Comment: Sim, é nullable(string), passei tudo para string na DTO, devido a um problema que debatemos bem aqui e ainda não encontrei solução, a não ser fazer essa "gambi", passando os campos float e double para string. Inclusive você participou bastante nessa situação, o qual me deu muita luz sobre diversos assuntos.
Comment: Erro meu, não vi que era string e string aceita null normal. Desculpe. Tem certeza que é o mesmo erro que continua? Não é um novo?
Comment: Cara, só não entendi se de um jeito funciona e outro não. Pra mim assunto resolvido, mas entendimento é fundamental, para não ocorrer e ficar patinando num problema que não é problema em si, e sim um erro lógico. Vou continuar minha leitura no assunto.
Comment: É assim: Quando você faz uma consulta sem o Enumerable.Select() você traz todas as linhas do banco, algo como um `SELECT * FROM ITENSLIB WHERE...`. Então se você não tiver um valor na linha ele vai trazer nada e vai quebrar sua propriedade, é diferente de fazer um `contexto.ItensLibs.Select` e não trazer essa propriedade do banco, nesse caso vai ser criado uma entidade com seu valor default (que no caso do float vai ser 0). No caso da DTO não é um problema ser nulo porque string em C# aceita nulo por padrão.
Comment: Bem, ok, valeu pela explicação. Entendi o porquê das coisas, nesse contexto, mas a questão do cast, quando eu terminar esse projetinho de 15 dias que tá mais de um mês, vou voltar ao assunto.
Answer: No SQL o tipo float é equivalente a double.
Já no .NET o apelido (alias) float é equivalente a single.
C# Reference
Então, aparentemente no seu banco de dados, a coluna Qtde é float mas no C# deve ser double ao invés de float pois eles são apelidos para tipos diferentes.
Comment: MurariAlex, nesse caso e em outros posts meus sobre o assunto, eu fiz a troca de float para `Single` ou `double` e o erro persistia. Inclusive possuo alguns posts sem solução aqui, sobre **CAST**, tive que transformar em meu DTO todos os **floats** e **doubles** em **string** para que pudesse funcionar o meu serviço.
Comment: Mesmo trocando no C# a propriedade `Qtde` de `float` para `double` não funciona? Se puder, faça esse teste e mostre qual a mensagem de erro ele retorna.

Erro de cast ao rodar o serviço rest


How to solve this integral ($\int _{\frac{\pi }{6}}^{\frac{\pi }{4}}\sqrt{1-\tan ^2\left(x\right)}dx$)

Question: $$\int _{\pi/6}^{\pi/4}\sqrt{1-\tan ^2\left(x\right)}dx$$
Hey, can you help me to solve this integral please? Thanks.
Comment: $y=\tan x$, then $y=\sin t$
Comment: Hint: http://integrals.wolfram.com/index.jsp?expr=%281-%28tanx%29%5E2%29%5E%281%2F2%29&random=false
Answer: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
\begin{align}&\color{#c00000}{\int_{\pi/6}^{\pi/4}\root{1 - \tan^2\pars{x}}\,\dd x}
=\int_{\pi/6 - \pi/4}^{\pi/4 - \pi/4}
\root{1 - \tan^2\pars{x + {\pi \over 4}}}\,\dd x
\\[3mm]&=\int_{-\pi/12 }^{0}
\root{1 -\bracks{\tan\pars{x} + 1 \over 1 - \tan\pars{x}}^{2} }\,\dd x
=-\ \overbrace{\int_{\pi/12 }^{0}
{\root{4\tan\pars{x}} \over 1 + \tan\pars{x} }\,\dd x}
^{\ds{\mbox{Set}\ t \equiv \tan\pars{x}}}
\\[4mm]&=2\ \overbrace{\int_{0}^{\tan\pars{\pi/12}}
{t^{1/2} \over \pars{1 + t}\pars{1 + t^{2}}}\,\dd t}^{\ds{t^{1/2} \mapsto t}}\ =\
4\int_{0}^{\root{\tan\pars{\pi/12}}}
{t^{2} \over \pars{1 + t^{2}}\pars{1 + t^{4}}}\,\dd t
\\[3mm]&=4\Re\int_{0}^{\root{\tan\pars{\pi/12}}}
{\dd t \over \pars{t^{2} + 1}\pars{t^{2} + \ic}}
=4\,\Re\int_{0}^{\root{\tan\pars{\pi/12}}}
\pars{{1 \over t^{2} + \ic} - {1 \over t^{2} + 1}}\,{\dd t \over 1 - \ic}
\\[3mm]&=2\,\Re\braces{\pars{1 + \ic}\bracks{%
\int_{0}^{\root{\tan\pars{\pi/12}}}{\dd t \over t^{2} + \ic}
-\int_{0}^{\root{\tan\pars{\pi/12}}}{\dd t \over t^{2} + 1}}}
\\[3mm]&=2\,\Re\braces{%
\pars{1 + \ic}\bracks{%
{1 \over \root{\ic}}\arctan\pars{\root{\tan\pars{\pi/12}} \over \root{i}}
-\arctan\pars{\root{\tan\pars{\pi \over 12}}}}}
\\[3mm]&=
2\root{2}\
\underbrace{\Re\arctan\pars{%
{\root{2} \over 2}\,\bracks{1 - \ic}\root{\tan\pars{\pi \over 12}}}}
_{\ds{=\ \color{#c00000}{\pi \over 8}}}\ -\ 2\
\underbrace{\arctan\pars{\root{\tan\pars{\pi \over 12}}}}
_{\ds{=\ \color{#c00000}{\arctan\pars{\root{2 - \root{3}}}}}}
\end{align}

$$
\color{#66f}{\large\int_{\pi/6}^{\pi/4}\root{1 - \tan^2\pars{x}}\,\dd x
={\root{2} \over 4}\,\pi - 2\arctan\pars{\root{2 - \root{3}}}}
\approx {\tt 0.1554}
$$
Answer: By using the two substitutions Norbert suggested we get the following
$$
I
=
\int _{\pi/6}^{\pi/4}\sqrt{1-\tan ^2\left(x\right)}\,\mathrm{d}x
=
\int _{1/\sqrt{3}}^{1}\frac{\sqrt{1-t^2}}{\ \ \ 1+t^2}\,\mathrm{d}t
=
\int _{a}^{\pi/2} \frac{\sin^2y -1}{\sin^2y+1}\,\mathrm{d}y
$$
First $y\mapsto \tan x$ then $y \mapsto \sin t$. Here
$a = \arcsin 1/\sqrt{3}$ for simplicity's sake. This can be rewritten as
$$
I = \int_a^{\pi/2} -1 + \frac{2}{1+\sin^2y}\mathrm{d}y = a-\frac{\pi}{2}+\int_a^{\pi/2} \frac{2}{1+\sin^2y}\,\mathrm{d}y
$$
The last integral can be solved by the Tangent half-angle substitution (Weierstrass substitution) $u = \tan y/2$. Hence
$$
\int_a^{\pi/2} \frac{2}{1+\sin^2y}\,\mathrm{d}y
=
\int\limits_{1/2\sqrt{2}}^{\infty} \frac{2}{1+8u^2}\,\mathrm{d}w
=
\int_1^\infty \frac{\sqrt{2}}{1+w^2}\,\mathrm{d}w
=
\sqrt{2}\left( \frac{\pi}{2} - \frac{\pi}{4}\right)
=\frac{\pi}{2\sqrt{2}}
$$
With finally $w/\sqrt{8}\mapsto u$. So our total integral equals
$$
\int _{\pi/6}^{\pi/4}\sqrt{1-\tan ^2\left(x\right)}\,\mathrm{d}x
=
\arcsin  \frac{1}{\sqrt{3}}+\frac{\pi}{4}\left( 2 - \sqrt{2}\right)
\approx
0.1554
$$
Where I left filling out the details of the substitutions to the reader.


Insert (Google ad) token in a template

Question: I want to insert a token from the Google Ad Manager module in a view.
But how do you insert a token like the ad_slot token in this module in a views template?
Comment: have you looked at `token_replace()` ?
Comment: Yes, i couldnt make it work. How should it be used?
I could only find documentation on how to use it with tokens provided by the node: http://api.drupal.org/api/drupal/includes!token.inc/function/token_replace/7

In this case, the token is provided by module
Answer: The Google Ad Manager module uses a filter for the tokens, not the Token module. You could call its internal function $content=_google_admanager_substitute_tags($text); to do the substitution for you, where you replace $text with [google_ad:ad_slot] but I am not sure if it will know enough to put all the google js in your page. Try it out, I guess.
Otherwise, you can do something like $content=theme('google_admanager_block', $gid, $google_ad); where $gid=variable_get('google_admanager_account',''); and $google_ad is your ad slot. That I've done all over the place myself with reasonable success.
Comment: I've just tried both ways with no result.
Comment: if you do a `print 'hello world';` does it show up, eg, to make sure everything else is working.  if you look at your resulting html, does the rest of the google javascript show up in the header of the page, eg, a `[script]` tag containing the GA_googleFetchAds() and so forth.  If not, something else is amiss as well.
Comment: Just checked the source code and it prints the following:

So it prints the script, but not with the ad_slot info.

In the header it shows:

GA_googleAddSlot("ca-pub-xxxx", "ad_slot_of_another_slot_normally_placed_with_blocks");

Currently this is what i have in php:
 $google_ad = the_ad_slot_id;
 $gid = variable_get('google_admanager_account','');

 echo theme('google_admanager_block', $gid, $google_ad);
Comment: well something is turning $gid and $google_ad into "c" somewhere....so I'd check your php code...also, the AddSlot is only set when cache is set in the theme function, and you don't seem to be doing that here, so something else is amiss "in there" as well...and perhaps it's because all of my suggestions have been for the drupal 6 version...if you are running drupal 7, functions/arguments might be different etc, too
Comment: if it is d6 v d7, a quick look in the code says that its theme args are more along the lines of  `array('id' => $gid, 'ad_slot' => $google_ad)` so try that instead of `$gid, $google_ad`.
Comment: that's it!! It works with array('id' => $gid, 'ad_slot' => $google_ad). Thanks a lot
Comment: sweet! I'll learn D7 eventually :)

Insert (Google ad) token in a template


No white-space, qual é a diferença entre as opções pre, pre-line e pre-wrap?

Question: Eu já sei que, ao usar white-space: nowrap, o texto não quebra quando ultrapassa o limite de um container. Porém eu percebi que essa propriedade no CSS possui as opções pre, pre-line e pre-wrap.
Dessas três últimas, gostaria de saber qual é a diferença entre casa uma delas. Gostaria de alguns exemplos.
Answer: A diferença entre cada um dos valores é basicamente a forma de tratar espaços.
No HTML, quando há 2 ou mais espaços no código-fonte, o navegador renderiza como apenas 1 espaço, e quebra de linha de texto no código-fonte também é tratado como 1 espaço. Por exemplo:

   texto1    texto2

Veja acima que entre "texto1" e "texto2" possui 4 espaços, mas o navegador só renderiza 1 espaço.
E aqui quando um texto vem abaixo do outro, essa "quebra de linha no código-fonte" entre "texto1" e "texto2" é tratada com 1 espaço:

   texto1
   texto2

Esse é o padrão do HTML. Porém, se você aplicar white-space: pre na div acima, todos os espaços são renderizados como estão no código-fonte, incluindo os espaços da indentação e quebras de linha, veja:

div{
  white-space: pre;
}

   texto1
      texto2

É uma espécia de WYSIWYG (o que você vê é o que você tem).
No caso do pre-line é diferente. Ele suprime mais de 1 espaço em apenas 1 espaço (o que é o normal no HTML) mas mantém as quebras de linha no texto como estão no código-fonte:

div{
  width: 100px;
  border: 1px solid #000;
  white-space: pre-line;
}

    Lorem     ipsum dolor
    sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Veja acima que entre as palavras "Lorem" e "ipsum" possui 5 espaços, mas é renderizado apenas 1 espaço. Ele mantém a quebra de linha do código-fonte antes do texto (entre a
 e o início do texto). Veja que no início do texto há uma linha em branco que é o espaço gerado pela indentação do texto na div.
No caso do pre-wrap, os espaços são preservados como estão no código-fonte, inclusive o espaço no início do contêiner, gerando uma nova linha antes do texto, por causa do espaço entre
 e o início do texto:

div{
  width: 100px;
  border: 1px solid #000;
  white-space: pre-wrap;
}

   Lorem     ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Resumindo:

pre

Mantém os espaços e quebras de linha como estão no código-fonte.

pre-line

Mantém as quebras de linha do código-fonte e suprime mais de 1 espaço em apenas 1.

pre-wrap

Mesma coisa do pre-line, mas mantém os espaços como estão no código-fonte, sem supressão.


Specifying the Error Ratio in Deming Regression

Question: We use Deming Regression for method validation in our clinical ELISA laboratory. As we run clinical trials this needs to be performed if we get a new reagent batch, batch of plates, new plate reader or a new operator etc.
An important part of Deming Regression is calculating the error ratio which is the ratio of the standard deviations for x and y; SDx and SDy. I can't find any information on how to derive these.
Obviously I know how to calculate the standard deviation but what data can one use for this? For example, if we buy a new instrument that reads the ELISA plates, we would run a selection of samples with a wide range of values and then compare the old and new instrument by Deming Regression to make sure they give comparable results. How do I know what the standard deviation is for each instrument and thus specify the error ratio?
I can provide references if required.
Comment: Repeatedly measure the same object multiple times and compute SD?
Comment: That seems very reasonable. The only issue is that it becomes extremely time consuming doing something like that with ELISA (as opposed to an automated analyser for example).

But I suppose that's the only option, right?
Comment: Well, maybe the company that produces the device can provide some estimates of the uncertainties. Check the manual.
Comment: I'm wondering if simply running measurements the measurements in replicates would be sufficient? The reason it's got me thinking is because ELISAs involve both human (pipetting) error and measurement/instrument error.
Comment: Fair enough. You need to repeat the whole pipeline, pipetting included. Unless you can assume that one error is much smaller than the other.
Answer: For reasons I don't understand Dr. Mack uses the ratio of the variances.  This is makes the Deming regression the same as a Geometric-Mean regression:
https://www.youtube.com/watch?v=kXzzlueX3tw&t=900s
https://iopscience.iop.org/article/10.1088/1742-6596/78/1/012084/pdf   <-- section 2.4
This solution evidently goes back to a 1935 paper by Dent:
DENT, B.M.; "On observation of points connected by a linear relation" Proc. Phys. Soc. 1935
A publicly available explanation is given here (equation 1.4.12):
https://pure.tue.nl/ws/portalfiles/portal/4259628/7802107.pdf
Jansen, J., & Barrett, J. F. (1978). On the theory of maximum likelihood estimation of structural relations. Part 1: One dimensional case. (EUT report. E, Fac. of Electrical Engineering; Vol. 78-E-78). Technische Hogeschool Eindhoven.
Ling Leng et al 2007 J. Phys.: Conf. Ser. 78 012084
DOI 10.1088/1742-6596/78/1/012084
Comment: Hi, welcome to CV! Please add references for your links in case they die in the future. And if possible, summarize their content a bit. Link-only answers are deleted on this site.
Comment: Antoine, Thanks for gently informing me of the rules.  I added a citation for the second link, but the first one is an online course that is a little tricky to cite.  I'll keep this in mind for future answers.


continuous $f:X\rightarrow X'$, $X,X'$ metric spaces properties

Question:
True or False, prove or provide a counterexample.
(a) If $B\subseteq X'$ closed, then $f^{-1}(B)\subseteq X$ is closed.
(b) If $B$ is a bounded subset of $X'$, then $f^{-1}(B)$ is a bounded subset of $X$.
(c) If $A\subseteq X$ and $x_0\in X$ and $f(x_0)\in \operatorname{Acc}(f(A))$ then $x_0\in \operatorname{Acc}(A)$.

My attempts:
(a) True.
Let $B$ be a closed set in $X'$. Suppose $x_0\in f^{-1}(B)$. Take $\epsilon>0$ : $B_{\epsilon}(f(x_0))\subset B^c$, which is open since $B$ is closed. Then $\exists\delta$ : $f^{-1}(B_{\epsilon}(f(x_0))\subset f^{-1}(B^c)$ So $f^{-1}(B^c)$ is open and $f^{-1}(B^c)$ is closed.
(b) False.
Counterexample: $X=X'=\mathbb{R}$. Take $f^{-1}(B)=(-\infty,1)$ and $f(x)=\ldots$ not sure if this is actually false.
(c) True.
For $f(x_0)\in \operatorname{Acc}(f(A))$ to be true, $\forall\epsilon >0: B_{\epsilon}(f(x_0))\cap f(A)\neq\emptyset.$ Does that imply that  $B_{\epsilon}(x_0)\cap A\neq\emptyset$?
Comment: For (c) any constant $f\colon \mathbb R \to \mathbb R$ with constant value $c$, say, also is a counterexample. For if e. g. $A = \{0\}$ and $x_0 = 1$, then $c = f(1) \in f(A)$, but $1 \not\in \mathrm{Acc}(A)$
Comment: For (a), it is maybe easier to work with complements. Let $B^c$ be the complement of $B$. It is open iff $B$ is closed. The inverse image of $B^c$ is the complement of the inverse image of $B$. So to say inverse image of a closed set is closed is equivalent to saying that the inverse image of an open set is open.
Comment: What is the definition of acc$(A)$? Also, for b) you can notice that any constant function from $\mathbb{R}$ to $\mathbb{R}$ is a counter-example. Since if $f(x)=c$ for all $x\in \mathbb{R}$, then $f^{-1}\{c\}=\mathbb{R}$ but $\{c\}$ is bounded.
Comment: $Acc(A)$ is the set of accumulation points of $A$
Answer: (a) is indeed true, but your proof as it stands will not work, because you picked $x_0 \in f^{-1}(B)$, so $f(x_0)$ will be in $B$, not $B^c$. You want to show $f^{-1}(B)^c$ is open, I think, so you need to pick $x_0$ in that set. Then indeed $f(x_0) \in B^c$, so as this set is open there is some $\epsilon > 0$ such that $B_{\epsilon}(f(x_0) \subset B^c$, as you then claim. Then you do not use the actual $\delta > 0$, but you probably mean to apply continuity of $f$ at $x_0$, so there is a $\delta > 0$ such that $f( B_{\delta}(x_0) ) \subset B_{\epsilon}(f(x_0))$. Then you skip a minor step: note that we now know that for every $x' \in B_{\delta}(x_0)$, $f(x')$ is in $B_{\epsilon}(f(x_0)) \subset B^c$, so that indeed $x' \notin f^{-1}(B)$, and this shows that indeed, $B_{\delta}(x_0) \subset f^{-1}(B)^c$, showing that the latter set is open, because every point in it is an interior point.
For (b) consider a constant map from say $\mathbb{R}$ to itself. The image is a singleton $B = \{c\}$, and the inverse image of $B$ is all of $\mathbb{R}$, unbounded.
For (c), the opposite is true: $x_0 \in \mbox{Acc}(A)$ implies $f(x_0) \in \mbox{Acc}(f(A))$, and this property characterizes continuity for $f$ (when this holds for all subsets $A$ and all points $x_0$). As it stands it fails: try the function $f(x) = x$ from $\mathbb{R}$ in the discrete metric ($d(x,y) = 1$ for $x \neq y$, $0$ otherwise) to $\mathbb{R}$ in the standard metric. Then $A = (0,1)$ has only $A$ as its accumulation points, as all sets are closed in the discrete metric, but in the image it has $[0,1]$ as its accumulation points, so taking $x_0 = 0$ or $1$ will be a counterexample.
In fact, this property characterizes closed maps, functions that map closed sets to closed sets.


CSS a:hover not working as hoped

Question: I'm trying to build my first site and am trying to use the "a:hover" feature in CSS but can't get it to work - the links look the same whether hovering or not.
Here's a snippet of my CSS file:
    /* main page elements */
    a:link
    {
      text-decoration: none;
      color:white;
    }

    a:visited
    {
      text-decoration: none;
      color:FFFFFF;
    }

    a:hover
    {
      text-decoration: none;
      color:blue;
    }

    a:active
    {
      text-decoration: none;
      color:blue;
    }

Any help appreciated.
Thanks,
Robert.
Comment: what is it doing wrong? Where is your HTML?
Answer: You need to finnish the text-decoration instruction :P
text-decoration: none;

or
text-decoration: underline;

Comment: Thanks for the answer. I actually had it like this but removed it just before posting here. I've put it back - still doesn't work.

a:link
{
  text-decoration:none;
  color:white;
}

a:visited
{
  text-decoration:none;
  color:FFFFFF;
}

a:hover
{
  text-decoration:underline;
  color:blue;
}

a:active
{
  text-decoration:none;
  color:blue;
}
Comment: Sorry - I've amended the original post.
Answer: I hope you need to change the color in hover state
Try something like this one
eg.
HTML

 Hover Me

css

 a
 {
     text-decoration: none;
     color:#000000;
 }
 a:hover
 {
     color:#3399FF;
 }

Answer: Your might be transitioning from a:active to a:hover, which has the same color. Therefore you see no difference. Try setting a unique color for a:hover, and see what happens.
It would also help if you make a jsfiddle.
Answer: Your issue is in the text-decoration: parts, if you remove them or use a valid syntax your CSS should work.

CSS a:hover not working as hoped


Calculated members: SSAS

Question: In the "Calculations" tab of an SSAS cube project, does "Measures" dimension represent all measures within the measure groups as well?
For instance:
Patron Revenue has measures actual win, cash in, cash out....
Patron Redemption has measures operator pay, redeeming dollars, redeeming comp...
In calculation tab,
[Actual Gross Profit] is calculated as
[Measures].[Actual Win]-[Measures].[Operator Pay]-[Measures].[Redeeming Comp]-[Measures].[Redeeming Dollars]
So, in this case, does the [Measures] dimension represent the measures such as actual win, operator pay, redeeming comp and redeeming dollars etc located in different measure groups?
Help appreciated!
Answer: Yes.
Just as [Measures] is treated as a dimension, each measure group/measure is treated like a dimension hierarchy/member, so that you can slice and dice in MDX across any "dimension"; this means you can do things like have a query sliced on two dimensions and a measure; with one dimension on rows, then either the measures on columns (with the dimension implicit in the values) or a dimension on the columns, with the measure implicit.
Comment: thanx jeremy...well I am not using MDX. WHat I am doing is, I am writing a TSQL query to verify the calculated measure works correctly. But, when I browse the cube and drag one of them down, the value it shows does not match with that of TSQL query.
Comment: How do I trace back the actual columns used/joined to get the result using TSQL as given by  [Measures].[Actual Win]-[Measures].[Operator Pay]-[Measures].[Redeeming Comp]-[Measures].[Redeeming Dollars] in MDX?

SO far, my approach has been a look up into the measure properties and find the table/view and the column name used.
The joining column has been a difficult part, because the DSV looks very messy and is hard to follow the lines.

Any suggestions appreciated

Calculated members: SSAS


How to configure DNS server to forward queries about particular domain AND all of its subdomains

Question: I have DNS server (linux box with bind9), which is authorative for some domains, and forward all other queries to external DNS server of my ISP provider.
So far no problem.
Now I want that queries about some specific domains were forwarded to my internal DNS server, f.e.:
zone "some_domain" {
       type    forward;
        forwarders {
                some_internal_dns_ip;
        };
};

So far still no problem, all works ok.
But then, I want also to forward some reverse DNS queries to my internal DNS. So, I have added:
zone "16.172.in-addr.arpa" {
        type    forward;
        forwarders {
                some_internal_dns_ip;
        };
};

And this doesn't work as I expect. Queries about "16.172.in-addr.arpa" (for example
1.16.172.in-addr.arpa) are resolved correctly, but reverse queries about full address (for example 184.108.40.206.in-addr.arpa) are not. I understand that my server should use here some recursive query, but could not configure it. I have already tried adding following options
recursion yes;
allow-recursion { 127.0.0.1; };
allow-recursion-on { 127.0.0.1; };

but with no success .  (I have used loopback address here, because I need this functionality only for my DNS host, and not for its clients)
Any suggestions?
Comment: I am confused. Do you have three servers; bind, ISP, and another internal server?  If so does the internal server resolve the request for 172.16.1.1?
Comment: Yes - Exactly, and yes, internal DNS server correctly resolves reverse query for 172.16.1.1. All other queries are resolved by external ISP DNS server (by using global "forwarders" option). What I want to achieve, is my bind9 server to be also able to resolve reverse queries about addresses like 172.16.1.1 (only on this bind9 server, it doesn't have to resolve it for clients using this bind server)
Comment: Why would forwarding of the reverse zone not work? Is the ISP server queried? Try using tcpdump.
Answer: This is because bind creates the "empty zones" by default. So, your name server is the master for "16.172.in-addr.arpa." zone and return with "NXDomain" for your answers.
If you define "empty-zones-enable no;" in named.conf this will work as you expect.
Comment: This was the explanation for my experiencing the same problem.
Comment: And for me as well, on Ubuntu 14.04
Answer: I had the same problem, you are just missing IN in your named.conf syntax:
zone "5.10.in-addr.arpa." IN {

    type forward;
    forwarders {10.5.0.1;};
};

zone "6.10.in-addr.arpa." IN {

    type forward;
    forwarders {10.6.0.1;};
};

It is confusing as master / slave zones don't need it.
Anyhow that's what fixed it for me.
Answer: Two approaches...

Make BIND a master for 16.172.in-addr.arpa. Within the zone file, use NS records to delegate to the other internal server.

OR

Make BIND a slave for 16.172.in-addr.arpa. Set the other internal server as a master.


Using descartes rule of sign

Question:
Use Descartes' rules of signs to discuss the possibilities for the roots of each equation. Do not solve equation.
  $$p(x)= x^3+5x^2+7x+1=0$$

$p(x)$ I saw no sign change
$p(-x)$ I saw 2 sign changes because $-x^3+5x^2-7x+1=0$.
I am stuck how is the answer $3$ negative roots for $p(x)$ and how do I get $1$ negative and $2$ imaginary roots for $p(x)$?
Answer: There are sign changes from $-x^3$ to $+5x^2$, from $+5x^2$ to $-7x$, and from $-7x$ to $+1$. So that is three sign changes.
Answer: A very late answer, hoping it will benefit someone in future:
The word you missed is "at most" - 3 sign changes means "it has at most 3 negative roots", and not that "it has 3 negative roots"

Positive roots:The rule states that if the terms of a single-variable polynomial with real coefficients are ordered by descending variable exponent, then the number of positive roots of the polynomial is either equal to the number of sign differences between consecutive nonzero coefficients, or is less than it by an even number. Multiple roots of the same value are counted separately.
Negative roots:As a corollary of the rule, the number of negative roots is the number of sign changes after multiplying the coefficients of odd-power terms by −1, or fewer than it by an even number. This procedure is equivalent to substituting the negation of the variable for the variable itself. - Wikipedia

As you have seen, $p(-x)= -x^3+5x^2-7x+1=0$ has three sign changes: and that assures that there are at most 3 negative roots or less than it by an even number.
Since cubic equations has 3 roots and one is essentially a real root, and since $p(x)$ has no positive roots, it has either all 3 negative roots or 1 negative root and two complex conjugates as roots. This is all we can infer from Descartes' rule of signs.
Now, solving we see that it has one real negative root, and two complex roots.

Using descartes rule of sign


OpenCmis client - create alfresco tags

Question: I'm trying to create a script to upload docs into an Alfresco repository using the opencmis library (python). Uploading the actual document is fine, but I'm bending my brain on how to add tags to the document.
I was thinking along the lines of:
<code>props = doc.getProperties()
tagname = ['test']
tag = {"cm:taggable": tagname}
doc.updateProperties(tag)
</code>
But this throws a http 500 error
Any idea's anyone?
Answer: I am fairly certain that tags cannot be manipulated via CMIS. Instead, use the Alfresco REST API. It has support for tagging.
Comment: IC, seems like I need to mix and match REST and CIMS, found this page which is useful to see what function is supported where. http://docs.alfresco.com/5.1/references/dev-api-func-tags.html
Comment: Jeff Potts is a 100% true, CMIS is limited for example you can't see if a person is a memeber of a site look to my post [Get if a user is in a specific alfresco site](http://stackoverflow.com/questions/38720618/get-if-a-user-is-in-a-specific-alfresco-site)
Comment: Well, with CMIS 1.1 , you can add the "cm:taggable" aspect using Python cmislib (by Jeff Potts!), as aspects are considered as secondary properties.
Use the "cmis:secondaryObjectTypeIds" property.
After that, I could not find a way to add tags afterwards, except through REST API which is kindof wourkaround.

OpenCmis client - create alfresco tags


Varnish 5 seconds delay

Question: I have a strange problem with varnish, it's in front of an API and it's caching the whole responses.
It mostly works fine, but from time to time a request will take 5 seconds (or rarely 10 seconds, or 15 seconds .. always an increment of 5) more than usual to return.
I've tried bypassing the HAProxy in front, same, and I checked, it does that wether the URL is already cached or not (I've checked the Age header). So it can't be the backend since the page is in cache, it's not what's in front of varnish, that leaves only varnish itself as the cause of that problem.
Any idea as to what could cause that 5 seconds delay ? I've checked varnishlog, during that delay varnish isn't doing anything. I've also tried manually making another request during that delay, and varnish answered fine so it's not frozen or anything, it works fine.
And at the end of that 5 seconds, it's outputting the log for the request as usual, nothing weird in it. Example :

<< Request >> 132712
Begin req 132711 rxreq
Timestamp Start: 1499701302.309413 0.000000 0.000000
Timestamp Req: 1499701302.309413 0.000000 0.000000
ReqStart 127.0.0.1 43955
ReqMethod GET
ReqURL /url
ReqProtocol HTTP/1.1
ReqHeader User-Agent: curl/7.38.0
ReqHeader Host: host
ReqHeader Accept: /
ReqHeader X-Forwarded-Proto: https
ReqHeader X-Forwarded-For: ip
ReqHeader Connection: close
ReqUnset X-Forwarded-For: ip
ReqHeader X-Forwarded-For: ip, 127.0.0.1
VCL_call RECV
ReqUnset X-Forwarded-For: ip, 127.0.0.1
ReqHeader X-Forwarded-For: ip, 127.0.0.1, 127.0.0.1
VCL_return hash
VCL_call HASH
VCL_return lookup
Hit 2147582482
VCL_call HIT
VCL_return deliver
RespProtocol HTTP/1.1
RespStatus 200
RespReason OK
RespHeader Date: Mon, 10 Jul 2017 15:10:00 GMT
RespHeader Server: gunicorn/19.7.1
RespHeader content-type: application/json; charset=UTF-8
RespHeader X-Varnish: 132712 98834
RespHeader Age: 1902
RespHeader Via: 1.1 varnish-v4
VCL_call DELIVER
RespHeader X-Cacheable: YES
RespUnset Server: gunicorn/19.7.1
RespUnset Via: 1.1 varnish-v4
RespUnset X-Varnish: 132712 98834
VCL_return deliver
Timestamp Process: 1499701302.309480 0.000067 0.000067
RespHeader Content-Length: 251799
Debug "RES_MODE 2"
RespHeader Connection: close
RespHeader Accept-Ranges: bytes
Timestamp Resp: 1499701302.309571 0.000159 0.000092
Debug "XXX REF 2"
ReqAcct 198 0 198 197 251799 251996
End

I realize varnish believes that was treated quickly, but on curl's side it took 5 seconds. Curl is used directly on the varnish server, so it's not network latency.
It's a bit hard to reproduce, I'm using a script that does queries in a loop and shows the curl time_total to finally get it to happen.
Could it be something Linux side ? Maybe some kind of limit, or a socket cleanup job or something that would pause the request. It happens maybe once every 400 or 500 requests, sometimes more, sometimes less.
Answer: The problem was DNS resolution, curl does a new DNS query each time and it looks like the resolver for this server (Google's 22.214.171.124) takes 5 seconds to answer, sometimes. Nothing to do with varnish, my bad

Varnish 5 seconds delay


Determining constant in a CDF

Question: I have a question that I literally have no idea how to begin, I was hoping someone could help me:

It says $X_1,X_2,\ldots,X_n$ is a sample from a distribution
It says that the Cumulative Distribution Function (CDF) is

$$F(x,\theta) = 1 - C/((x-\theta)+3)^4,\quad x > 0, \theta > 0$$
The instructions now say

determine the constant C (no computation required) and determine the
  pdf f(x).

Can anyone point me in a direction of a resource? or give me a hint as to how to get started? I have no clue what this distribution function is at all!
Comment: The parameter $\theta$ has to be $\le 3$. Otherwise we do not have a cdf on $(0,\infty)$.
Answer: If $F(x,\theta) = 1-\frac{C}{((x-\theta)+3)^4}$ is a cumulative distribution function, then we know that it must satisfy certain properties, namely:

$F(x,\theta) \to 0$ as $x\to -\infty$;
$F(x,\theta) \to 1$ as $x\to \infty$;
$\frac{dF}{dx} \ge 0\ \forall x$.

The probability density function is simply $\frac{dF}{dx}$, by definition. To find the constant $C$, we need only look at the first few properties. Hint: for any arbitrary choice of $\theta$, what does $\frac{1}{((x-\theta)+3)^4}$ look like?
Comment: If $\theta = 4$ and $x=1$, then $F$ is undefined unless $C=0$. But if $C=0$ then property 1 cannot hold. What am I missing?
Comment: @Arkamis Thanks, and I really don't mean to slow the discussion down. But is $\theta = 4$ an allowable parameter value? If so, then for that parameter value, doesn't the graph have a gigantic singularity at $x = 1$?
Comment: @JasonZimba where did theta=4 and x=1 come from? Why couldn't it be C=1, since x is a realization of a random variable and could be anything in the support?
Comment: Sorry if my comment was not on point - I am not an expert on probability theory. But just reading the question, it seems to say that $F(x,\theta)$ is a function of two variables, where the two variables must both be positive. Well, 1 and 4 are both positive. So shouldn't I be able to evaluate $F$ at those values?
Comment: @JasonZimba Your first point says that $X_1,X_2,\ldots,X_n$ are sampled from the distribution. This tells me that the random variable is $x$, not $\theta$. Instead, $\theta$ is a parameterization of the distribution. This is common. So you don't really have a two-variable distribution, but rather a univariate one with a parameter $\theta$.
Comment: @Arkamis is this a pareto?? Because it doesn't look like any of the forms here: http://en.wikipedia.org/wiki/Pareto_distribution#Pareto_types_I.E2.80.93IV
Comment: @Gosset Probably not; there's no reason I would suspect it to be.
Comment: @JasonZimba Yes, it would have a singularity wherever $x = \theta - 3$. But then it wouldn't be a CDF. So, there must be conditions on $\theta$ that avoid this condition. We're *given* that it's a CDF, so you can assume that $\theta$ implicitly meets these restrictions.
Comment: OK, then I think we need $\theta \leq 3$. I was just confused because the constraint given by OP is $\theta > 0$.
Comment: @JasonZimba It's just forcing you to think a little bit. There are *two* constraints on $\theta$: $\theta > 0$ which is enumerated explicitly, and $\theta \le 3$, which is implicit given that we're given $F$ as a valid CDF.
Comment: I would call it sloppy, personally.
Comment: I don't know. I think it induced you to ask a very good, natural question and to think carefully about the problem and the definitions.
Comment: I respect your view. I do think you're giving the person who wrote the question a lot of credit....
Comment: More domain confusion. In your reply, you stated a condition for $x\rightarrow -\infty$. But isn't the CDF only defined for $x > 0$?
Comment: Yes, so effectively the condition $F \to 0$ as $x \to -\infty$ can be replaced with $F \to 0$ as $x \to 0$ and $F = 0$ for $x \le 0$. These latter conditions obviously satisfy the former.
Comment: For what it's worth, although this may seem like needless generalization, it actually makes sense when you begin to look at probability theory in a measure-theoretic sense. Having these general definitions allows us to write theorems without having to consider a bevy of special cases.
Answer: Let $F(x,\theta)$ be defined for $x>0$ and $\theta < 3$ by $$F(x,\theta) = 1 - {C\over(x-\theta+3)^4}\,.$$ If $F$ is a CDF in $x\in (0, \infty)$, then what must be the value of $C$?
Well, as $x\rightarrow 0$ from the right we have $$F(x,\theta)\rightarrow 1 - {C\over (3-\theta)^4}\ .$$
For $F$ to be a CDF, this limit must be zero, so that $C = (3-\theta)^4$.
That makes $$F(x,\theta) = 1 - {(3-\theta)^4\over(x + (3-\theta))^4}\,.$$
Note that $F\rightarrow 1$ as $x\rightarrow \infty$, as required for a CDF. It can also be verified that ${\partial f\over\partial x} \geq 0$.
Comment: I just want to thank everyone who contributed to this answer, it has been most instructive. I was looking at this problem in an incorrect manner, attempting to identify some kind of common distribution, when I should've been considering this as an algebraic issue. Thanks again, all.

Determining constant in a CDF


Using pyserial without installation?

Question: I am working on a PYQT-QGIS Application, I want my application to require least number of external dependencies.(ideally none)
Pyserial is on of main library that I am using, so I was thinking to use this library without installation and let it be a part of my package.I remember using an old pyserial library for QGIS Plugin.
Question:
Is it still possible to use pyserial lib without installation? some pointers would be helpful.
Answer: Looking at the current pyserial package setup.py, there seems to be some additional setup which is run when installing the egg:
setup(
    name = "pyserial" + suffix,
    description = "Python Serial Port Extension",
    version = version,
    author = "Chris Liechti",
    author_email = "email@example.com",
    url = "http://pyserial.sourceforge.net/",
    packages = ['serial', 'serial.tools', 'serial.urlhandler'],
    license = "Python",
    long_description = "Python Serial Port Extension for Win32, Linux, BSD, Jython, IronPython",
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: Python Software Foundation License',
        'Natural Language :: English',
        'Operating System :: POSIX',
        'Operating System :: Microsoft :: Windows',
        #~ 'Operating System :: Microsoft :: Windows :: Windows CE', # could work due to new ctypes impl. someone needs to confirm that
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.3',
        'Programming Language :: Python :: 2.4',
        'Programming Language :: Python :: 2.5',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.0',
        'Programming Language :: Python :: 3.1',
        'Programming Language :: Python :: 3.2',
        'Topic :: Communications',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Terminals :: Serial',
    ],
    platforms = 'any',
    cmdclass = {'build_py': build_py, 'build_scripts': build_scripts},

    scripts = ['serial/tools/miniterm.py'],
)

Of note is the cmdclass and scripts sections. The egg is building the .py, .pyc and script files and appears to take into account the machine itself while doing so. Unless you prebuild the egg and deploy on the same platform/python etc. it may not work to just drop it in.
I highly recommend looking into Buildout for deploying your applications. It  handles dependencies/deployment issues for you in a reproducible and productive way. I currently use it to deploy arduino projects with Pyserial/PYQT/Pyside and it works very well. I will hopefully be able to share my GIT with an Arduino recipe on a future tutorial of this kind of thing.
Buildout can either grab the packages from the internet, or you can pre-load the eggs you want into your installer. It essentially allows your project to have a dedicated virtual environment with all eggs/scripts "installed" and configured just for it. This is especially useful for more complex packages like iPython Notebook, Django, or in your case PyQT/pyserial, since it actually installs/builds the eggs as if installing on the machine directly, but does so in a way that will not affect other tools/projects.
http://www.buildout.org/en/latest/

Using pyserial without installation?


Is it possible for a non reactive Client (RestTemplate) to consume a Reactive REST API (WebFlux)

Question: Is it possible for a RestTemplate to consume an endpoint which is reactive based (Spring WebFlux)? I understand that the main idea of reactive programming is to avoid blocking and make better use of threads (eliminate thread per connection model) so what happens if my Client is non reactive?

Will I still be able to call the service even if it is in a blocking
manner?
To achieve full reactiveness (non blocking) both Client and Server
must be reactive?
Answer:
Yes, that is not relevant to the clients of Reactive applications. The reason is that this is a regular HTTP call.
Each may be fully reactive on its own. Having said that, if you use WebFlux in both Client and Server you will have a system that is as a whole reactive. But there is nothing forcing you to do this. You can have only one of the services as a Reactive application. It comes down to your needs and context.


Is Dalcrose Eurhythmics appropriate for beginning performers?

Question: Are Dalcrose Eurhythmics concepts appropriate for newly beginning instrumentalists or do they rely on instrumental techniques that are only acquired later? If they are appropriate, what are some of the benefits that have been said to come from beginning Eurhythmics at an early stage?
Comment: I tried to reword so that the questions asked in the main text ask for citations rather than entirely opinion-based answers. Both answers give some evidence, so the question now fits more closely.
Comment: I don't follow the localization comment. I believe there are experts on this site which will have heard of Eurhythmics and can properly answer the question. Also, open ended discussion questions ("which methods should I look for") are probably discouraged?
Comment: Although I'm new to StackExchange, I also don't agree that this is too localised - unless my question on Kodaly was also too localised. I've certainly heard of Dalcrose Eurythmics in the context of music education and conducting, and would be able to provide a brief answer. I do agree that the title could be shortened - again, I'm new to how StackExchange does things, but perhaps simply "Is Dalcroze Eurhythmics appropriate for beginner performers?" and then check for typos as ogerard says.
Comment: @Mich Sampson: I like your version of the title and after reading you and blueberryfields, I agree that this may not be too localized. I would suggest the Original Poster to add a reference link for Dalcroze Eurhythmics.
Comment: I think this is too subjective, not too localized.  You need to provide some criteria for good answers.  "Is is appropriate?" and "Should one study it?" is just asking for opinionated answers with no evidence.  Check out [http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/)
Answer: I've come across Dalcroze Eurhythmics as part of a class on Kodaly - our teacher gave us a taster of some DE exercises. My impression is that (rather like Alexander Technique) it could be extremely useful to beginner musicians/performers because it embodies good habits before you have a chance to develop the bad ones!
Internalising pulse and rhythm in the body is essential for later playing. Musicians who have trouble with this often exbibit problems such as speeding up, over-intellectualising (e.g. only being able to play rhythms through counting rather than feeling them), or over-controlling the body (a problem I experience in conducting).
As Kyle says, the exercises are also massively fun - so a beginner player struggling with various technical and mental challenges might find these very helpful in keeping the momentum and joy going!
(Your question made me look up DE again, so I might now have talked myself into giving it a go - alas, to fix the bad habits I already have!)
Answer: The preparatory school at one of the music schools I attended offered this for children learning music. I can't point you towards any studies, but there are two things that come to mind why I think that this is a great idea.

Learning good rhythm from the start by feeling it in your whole body makes a lot of sense. This way, as you a learn an instrument you will be able to focus son the instrument more.
I saw some of these classes being done with kids and everyone was having lots of fun. They are fun for adults as well :-)
Comment: +1, my kids take Dalcroze Eurhythmics classes at their Suzuki Institute summer program and it's one of their favorite things because it's so fun.


Probability of winning after playing a 5 set match

Question: In the 4 majors of Tennis, the men in the singles competition need to play the best of 5 sets. From what I have seen, is that if a player plays a 5 setter and wins, they are going to have less of a chance of winning the next match than if they had won by 3 sets (just my observation).
This is considering more about endurance, stamina and fatigue rather than skill or who they play against in the next round.
Have there been such analysis done and if so what is the probabilities.
Like saying that the same player against the same opponent in the next round is a % greater chance of losing if they played a 5 set match beforehand instead of a 3 set match.
Comment: I suspect that stronger players win more matches in 3 sets than weaker players, and subsequently are more likely to win their next set. It seems like it would be important to control for that.
Comment: Yes... but taking the actual player ability out of the equation... would they be less likely to win the next match if they played a 5 setter instead of a 3 setter. This would imply that the 5 set match was against someone stronger and therefore take more out of them. But I am talking about the next match they play.
Answer: I did not see any such statistics.
Maybe just example:
Roger Federer on US Open 2017
1st round Tiafoe 3-2
2nd round Juznyj 3-2
3rd round Lopez 3-0
4th round Kohlschreiber 3-0
QF DelPotro 1-3
So if you do not take into the account also the rankings of the opponent, it can be always misleading. But even with rankings it can be misleading too (see Federer example, who after two 5 sets matches, won next one really easily)
So would be nice to see statistics you mention, but it would have no value for any further evaluations.
Comment: With all due respect... one player (arguably the best in history) over a couple of matches will not provide any statistical information in this area as a whole
Comment: that was just example. Still think, that statistics you would like to see will have no value