Instrumental variables regression Vs Linear Regression for price elasticity

Question: Based on comment here that What do "endogeneity" and "exogeneity" mean substantively? should we use linear regression or instrumental regression for price elasticity? As price and demand might have some endogeneity?
Linear regression cannot handle endogeneity phenomenon if or goal is a causal model with endogenous variables. i.e. if we want to predict if my price is x what will be demand in a real world scenario. To cure this, instrumental regression is used. It makes logical sense that Instrumental regression SHOULD be used in this situation. However, i still wanted some expert comment if this is the right thing to do as i didn't find any paper which advocates using IV regression for price elasticity causal model.
Comment: Please, don't cross post on multiple sites. Since an answer has been provided on CV, I would suggest to delete [the duplicate](http://economics.stackexchange.com/q/10808).
Comment: @chl I think price elasticity is a multi-discipline subject and not restricted to statistics or economics alone. Hence posts in both statistics and economics forum. I think economists might have different approach or opinion. Let me know if you still think the other post needs to be deleted. Thanks
Comment: I agree that this might of interest for different communities, but see our [recent Meta discussion](http://meta.stats.stackexchange.com/q/2917/930) (and related links) about cross-posting.
Comment: Fair point, i edited the post in economics forum to make it suitable for the other forum instead of copy-pasting question word by word as suggested by Scortchi in the accepted answer. Thanks
Answer: In general, you cannot use plain OLS on market data to estimate demand elasticity. The one, unusual, exception would be if supply was not price sensitive (the supply curve was a straight up and down line with the same price for every quantity).  The same goes for supply elasticity.  See this link  which explains it well.  You can also see Greene's Econometric Analysis textbook (edition 5 or 7, 5 is available for free in pdf online) which covers this topic thoroughly.  I will make an informal attempt at explaining below.
Suppose we want to estimate a linear supply and demand curve, something like;
$$
\begin{array}{llc}
 q^s_t &= \alpha_0 + \alpha_1 p_t + \alpha_2 w_t+ u_t&(Supply) \\
 q^d_t &= \beta_0 + \beta_1 p_t +\beta_2 y_t+ v_t&(Demand)
\end{array}
$$
Where $q^s_t=q^s_t$ is log quantity, $p_t$ is log price,  $w_t$ are the log input costs, and $y_t$ is log consumer income. (you can have other explanatory variables too if you like, but this is the basic case).
With the above specification, the demand and supply price elasticities are
$$
 \frac{\partial q^s_t}{\partial p_t}= \alpha_1\;\;(Supply)\;\;\;\;
 \frac{\partial q^d_t}{\partial p_t} = \beta_1\;\;(Demand)
$$
BUT THE ABOVE CANNOT BE ESTIMATED WITH OLS because price is endogenous.  Why? because, for the market to clear, price and quantity are decided simultaneously with both demand and supply side mechanisms.  For example, a firm may change it's prices in response to increases or decreases in it's competition.  Such variation in prices is not exogenous but rather caused by shifts in $q^s_t$.  This reverses the order of causality that would be implied by an OLS regression model of the above supply and demand functions.
Demand elasticity is generally upward bias when estimated with OLS and I am pretty sure supply elasticity is downward bias (but check the references above too, I think the bias is usually attenuating (toward 0) in all cases).
There are two prominent econometric methodologies for estimating demand/supply curves.  These are

Structural equation modeling: $$ \begin{bmatrix}q_t \\ p_t \end{bmatrix} =  \begin{bmatrix}\pi_0 \\ \omega_0 \end{bmatrix} + \begin{bmatrix}\pi_1 & \pi_2 \\ \omega_1&\omega_2 \end{bmatrix}\begin{bmatrix}w_t \\ y_t \end{bmatrix}+\begin{bmatrix}e_{1,t} \\ e_{2,t} \end{bmatrix}$$ which is a multivariate likelihood.
Instrumental Variables (as suggested in your question).  In the case of demand this is: $$\begin{array}{llc}
  p_t &= \omega_0 + \omega_1 w_t + \omega_2 y_t + e_t&(First\;Stage) \\
 q^d_t &= \beta_0 + \beta_1 \hat p_t +\beta_2 y_t+ v_t&(Second\;Stage)
\end{array} $$

$w_t$ works as an instrument because it acts like an exogenous "shifter" in supply.  The basic idea is that by moving the supply curve up and down and recording the equilibrium quantities and prices, we can trace out the demand curve. The assumption here is that the suppliers cannot control their input costs (this is not always true when suppliers can negotiate their input costs as in oligopsony but we assume it is here). For supply we would use the same methodology but with $y_t$ as the instrument.
Comment: Interesting to know use of SEM. I believe IV regression might be most frequently used than SEM given the challenge it is to build an SEM model. Thanks for sharing the assumption around 'input cost'
Answer: The original application of the instrumental variable approach was in the estimation of elasticities! Wright (1928) referred to IVs as 'curve shifters' in his use of them to estimate the elasticity of flaxseed (referred to here).


Mysql select mesma coluna de 6 tabelas diferentes

Question: Tenho 6 tabelas MySql que contém uma coluna DE MESMO NOME  descricao (varchar) e gostaria de criar uma nova tabela com os dados desta coluna agrupados (sem repetir).
Gostaria de saber como selecionar o campo "descricao" das tabelas "tabela1", "tabela2","tabela3","tabela4","tabela5","tabela6" e armazenar em uma nova tabela.
Estou usando mysql 8 ou mysql 5.7
Comment: Gostaria de deixar uma reflexão, você realmente necessita realizar o armazenamento de dados duplicados em outra tabela do seu banco de dados? Apesar de isso ser possível, são raros os cenários em que isso se torna viável.
Comment: já tentou algo Eduardo? coloque pra pergunta para podemos seguir o mesmo raciocinio ou ver se só basta algo
Comment: Descrevendo o problema geral você vai conseguir apenas uma resposta geral. Exemplo: "Como construir uma casa?", "Use blocos e cimento, construa paredes sólidas.". Em vez disso pergunte algo específico e respondível de forma útil: "Como levantar uma parede usando esse tipo de bloco com tal inclinação e de tal altura de forma segura?", resposta: "Posicione os blocos no formato tal, execute esse algoritmo de colocação de blocos, não use essa ferramenta pois há o risco tal. Se possível adicione mais informações como nome das tabelas envolvidas, para que facilite adaptar a resposta para a pergunta.
Answer: Da mesma maneira que se é possível realizar um Select dentro de outro Select, o MySql permite realizar outras operações como um SELECT dentro de um INSERT.
Supondo que temos 2 tabelas como exemplo, e que gostariamos de realizar um SELECT de uma tabela, e realizar um INSERT em outra.

Tabela_A - Colunas: id, titulo, descricao, valor.
Tabela_B - Colunas: id, descricao

Resultado:
INSERT INTO Tabela_B (id, descricao)
SELECT (id, descricao) from Tabela_A;

Como o seu cenário, necessita de fazer select em mais de uma tabela, você pode, simplesmente fazer o insert, do resultado da UNION das duas tabelas.
INSERT INTO Tabela_B (..., ...)
(SELECT (..., ...) from TABELA_A
UNION
SELECT (..., ...) from TABELA_C);

Comment: Realizada a correção, para se adaptar a pergunta (sem repetir).
Comment: Usar o UNION me retorna erro de SQL:

`INSERT INTO tabela_resultado (descricao)
(SELECT (descricao) from tabela_A
union
SELECT (descricao) from tabela_B);`
Comment: Isso provavelmente ocorra pois o nome de suas tabelas não são ```Tabela_A```, e  ```Tabela_B```, você deverá fazer o ajuste de acordo com o nome de suas tabelas.
Comment: Claro que os nomes descritos são fictícios @vitor-subhi


When to use a tpl.php file instead of a .css file?

Question: This is my first question on Drupal answers, so be kind to me :)
I'm fairly new to Drupal, and indeed web developing in general.  I have been working on my first site for a few months now, learning as I go.
In the past month, I have figured out how to make my own sub-theme of the one I was using.  I have been using the sub-theme to adjust the "little niggles" that I have with page formatting directly.  So far, I have been doing this by adding little snippets of css to a .css file in the sub-theme - and trying to keep this file as DRY as possible.
This has been working well for me, but when reading around, all I see is discussion of modifying/using .tpl.php files, which is making me wonder if I'm missing something and/or setting myself up for major problems as this this .css file grows?
TL:DR What are the problems and/or disadvantages of using a single .css file to make styling adjustments on my drupal site?
Comment: Keep doing what you're doing if the markup of your theme suits you. CSS files and Template files both work with each other and interdependent on each other more or less.
Answer: If your real question is more along the lines of:

Should I make the CSS conform to the markup, or make the markup conform to the CSS?

Then that's just a judgment call, there's no right or wrong answer. Go with what you feel comfortable doing. Some people love the plethora of classes Drupal adds by default, some people hate it. Some people prefer the Bootstrap approach (class, class, class), some people prefer the Susy approach (as few classes as possible, ostensibly). Neither is right or wrong, just different.
Read on for answers to the specific posed questions...

When to use a tpl.php file instead of a .css file?

The literal answer to that is simply "never".
A CSS file and a template file are for different things, and contain different things. You wouldn't put markup in a CSS file, and you wouldn't put CSS in a template file (except perhaps in rare circumstances like if you were inlining the above-the-fold content or something).

What are the problems and/or disadvantages of using a single .css file to make styling adjustments on my drupal site?

There are no problems or disadvantages per se. It's arguably better to split your CSS into multiple files, simply for modularity's sake, but those are all going to be aggregated back into one when the site goes into production mode anyway (assuming the CSS you're talking about is "every page" CSS; you haven't mentioned otherwise).
Basically go with what feels comfortable, by your organisation's standards, or whatever general advice you find and like about organising CSS files. Drupal doesn't mind how you do it.
Comment: Many thanks for the full-some answer.  It appears I hadn't quite appreciated the differences between the files (which is why I asked the question).  At least there is no downside to what I am doing currently.  I'm far from the level of using Bootstrap, or one of the "bare-bones" base themes, I guess I'll need to look into tpl files at that point?
Comment: You're welcome - the template files are used to control the HTML markup, so you only really need to look at those when the existing markup (for nodes, user profile pages, comments, etc) isn't what you'd like it to be. That might be driven by a need to style elements in a certain way using CSS, or maybe there's too much markup being produced and you'd like to slim it down, maybe you need to add microdata, and so on. Basically, if you're looking at some markup that a module or theme is outputting, and you're thinking "this needs to change", that's when you need to dive into a template file
Comment: @Jabelpeeps Bootstrap is not really that great thing that most people make it out to be ;) I don't think it's future proof, plus it is already going old. Check [this post](https://www.drupal.org/node/1801582#comment-6553686) about the downfalls of bootstrap on the discussion about [including a new framework based theme in core](https://www.drupal.org/node/1801582) on d.o if you feel like doing some reading ;)


Validador de HTML do W3C acusa "Empty heading"

Question: Estou tentando validar meu html e ele está me dando a seguinte mensagem:
Line 328, Column 34: Empty heading.

A internet no controle

Deu a entender que o titulo  está vazio, mas veja que ele tem um  conteúdo.
Link para o html no codepen
Comment: Poderia postar o código todo da página, ou publicá-lo em algum lugar adequado? Pode remover algumas partes, desde que o validador continue apontando o erro.
Comment: Tem certeza que a origem do erro é esse h3? E ele já está preenchido no próprio HTML, ou seria preenchido mais tarde (por exemplo, com ajax)?
Comment: Então... o validador informou a linha a coluna e esse trecho do codigo que se encontra nesta linha. Não tem ajax, ele está dentro do html mesmo.
Comment: Postei no pastebin [um exemplo mínimo que reproduz o problema](http://pastebin.com/PtdS5afq). Note que se tirar a tag `` o problema desaparece, de modo que ela deve estar envolvida de alguma forma.
Comment: Além do código da página, informe também qual validador você está utilizando (seria [o do site da W3C](http://validator.w3.org/)?) e qual a versão-alvo (HTML5, HTML 4.01 strict, HTML 4.01 transitional...)
Comment: estou utilizando o [http://validator.w3.org/check](http://validator.w3.org/check)
Comment: estou usando o HTML5
Comment: Pode verificar esse CodePen? Eu abri aqui e não nenhum HTML.
Comment: [http://codepen.io/rogeralbinoi/pen/cwudF](http://codepen.io/rogeralbinoi/pen/cwudF)

Dê uma olhada
Comment: Acho que entendi. Semanticamente não é certo colocar um h3 dentro de uma tag figure. Se eu trocar a tag figure e usar uma div, resolve o problema.

Obrigado a todos que me ajudaram!
Comment: Olha que legal, a pessoa que cuida do validador do W3C respondeu! Talvez seja o caso de você marcar a resposta dele como aceita. É um bug do validador.
Answer: O significado de "empty" nesse caso não é que a tag não possui conteúdo; é que essa tag não faz referência a uma seção. O significado semântico de um header é que ele é "o cabeçalho de uma seção", e não simplesmente uma opção de formatação (como strong ou em).
Veja essa pergunta no SOen para mais detalhes. Ainda estou pesquisando sobre o que deve ser feito para consertar isso, quando descobrir posto aqui.
Atualização: no seu caso, o uso do cabeçalho dentro de um article estaria correto, o problema parece ser por esse article estar dentro de um figure. Há vários usos para esse elemento, mas não conheço as consequências de se usá-lo dessa forma. De modo que um meio de solucionar esse problema seria colocar esse article em outro lugar (por exemplo numa div, como você diz ter feito com sucesso nos comentários).
Comment: Será que precisaria estar dentro de um ``? Nunca vi esse erro antes!
Comment: Eu também pensei nisso, colocar ele dentro de um    'section'...
Comment: @bfavaretto Provavelmente... `` por exemplo. Também nunca tinha visto esse erro antes, teria que fazer uns testes.
Comment: Olá, este h3 esta dentro de um article ...
Comment: Vou colocar no codepen, só um minuto
Comment: Coloquei um link com o code html, ignore os demais erros, pois tirei algumas partes do html
Answer: Eu mantenho o validador de HTML5 do W3C. O problema que você reportou é causado por um bug no código do validador. Não é o comportamento esperado. O
 certamente não está vazio, portanto a mensagem de erro está errada mesmo. Vou tentar consertar esse bug logo. Obrigado por perceber o problema.

I'm the maintainer of the W3C HTML5 validator. The problem reported here is caused by a bug in the validator sources. It's not intended behavior. The
 is definitely not empty. So in this case the error message is just wrong.  I'll try to fix this validator bug soon. Thanks for catching it.
Comment: Thank you very much for your feedback. I wasn't expecting this to be read by anyone who doesn't speak Portuguese! You are always welcome here for this kind of feedback, feel free to post in English and we'll translate your answers.
Comment: Hello again. Just to close the loop on this, I wanted to say: I did fix this problem a few months ago in the W3C validator. Sorry for not following up on it here before now, and thanks again for catching it. If you notice other problems please open an issue at https://github.com/validator/validator/issues or send e-mail to firstname.lastname@example.com or to me directly at email@example.com. Cumprimentos
Answer: Acho que entendi. Semanticamente não é certo colocar um h3 dentro de uma tag figure. Se eu trocar a tag figure e usar uma div, resolve o problema.
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>Teste</title>

                    Ponto de vista
                    Entrevista

A internet no controle

Atualmente, publicam-se on line muito mais informações sobre nós mesmos     do que jamai antes, todos estes dados estão sendo coletados por organizações...

Removendo a tag figure e usando uma div resolve.
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Teste</title>

                Ponto de vista
                Entrevista

A internet no controle

Atualmente, publicam-se on line muito mais informações sobre nós mesmos do que jamai antes, todos estes dados estão sendo coletados por organizações...

Ou então pode-se usar um span no lugar do h3, caso eu queira usar a tag figure.
<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>Teste</title>

                    Ponto de vista
                    Entrevista
                    A internet no controle

Atualmente, publicam-se on line muito mais informações sobre nós mesmos     do que jamai antes, todos estes dados estão sendo coletados por organizações...


How to record array of ints, and print frequency of duplicates

Question: Note:  Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:

Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered.  After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
  In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.

This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);

    public static int[] userIntegers()      // this method will build the array of integers, stopping when an out-of-range input is given
    {
            System.out.println("Enter the number of integers to be recorded:  ");
            int numInts = scan.nextInt();

            int[] userArray = new int[numInts];
            int i = 0;
            while(i < numInts)
            {
                    System.out.println("Enter an integer between 1-50 inclusive:  ");
                    int userInteger = scan.nextInt();
                    if(isValidInteger(userInteger))
                    {
                            userArray[i] = userInteger;
                            i++;
                    }
                    else if(isValidInteger(userInteger) == false)
                    {
                            System.out.println("Try again.");
                    }
            }
            return userArray;
    }

    public static void occurrenceOutput(int[] input)         // this method will print the occurrence data for a given array
    {
        int[] occurrenceArray = new int[51];

            int j = 0;
            while(j < 51)  // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
            {
                    for(int eachInteger : input)
                    {
                            occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1:  occurrenceArray[j];
                    }
                    j++;
            }

            int k = 0;
            for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
            {
                    if(eachOccurrence > 1)
                    {
                            System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
                    }
                    k++;
            }
    }

    public static boolean isValidInteger(int userInput)     // checks if a user input is between 0-50 inclusive
    {
        boolean validInt = (51 >= userInput && userInput >= 0)?  true:  false;
            return validInt;
    }

    public static void main(String[] args)
    {
        occurrenceOutput(userIntegers());
    }
}

Can someone point me in a more elegant direction?
EDIT:  Thanks for the help!  This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
    public static void main(String[] args)
{
            getUserInputAndPrint();
            getIntFreqAndPrint(intArray, numberOfInts);
    }

    private static int numberOfInts;
    private static int[] intArray;
    private static int[] intFreqArray = new int[51];

    public static void getUserInputAndPrint()
    {
            //  The user is prompted to choose the number of integers to enter:
            Scanner input = new Scanner(System.in);
            System.out.println("Enter the number of Integers:  ");
            numberOfInts = input.nextInt();

            //  The array is filled withchInteger = integer; integers ranging from 0-50:
            intArray = new int[numberOfInts];
            int integer = 0;
            int i = 0;
            while(i < intArray.length)
            {
                    System.out.println("Enter integer value(s):  ");
                    integer = input.nextInt();
                    if(integer > 50 || integer < 0)
                    {
                            System.out.println("Invalid input.  Integer(s) must be between 0-50 (inclusive).");
                    }
                    else
                    {
                            intArray[i] = integer;
                            i++;
                    }
            }

            // Here the number of integers, as well as all the integers entered are printed:
            System.out.println("Integers: " + numberOfInts);
            int j = 0;
            for(int eachInteger : intArray)
            {
                    System.out.println("Index[" + j + "] : " + eachInteger);
                    j++;
            }
    }

public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
    //  Frequency of each integer is assigned to its corresponding index of intFreqArray:
    for(int eachInt : intArray)
    {
        intFreqArray[eachInt]++;
    }

    //  Average frequency is calculated:
    int totalOccurrences = 0;
    for(int eachFreq : intFreqArray)
    {
        totalOccurrences += eachFreq;
    }
    double averageFrequency = totalOccurrences / numberOfInts;

    //  Integers occurring more than once are printed:
    for(int k = 0; k < intFreqArray.length; k++)
    {
        if(intFreqArray[k] > 1)
        {
            System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
        }
            }

            //  Average occurrence of integers entered is printed:
            System.out.println("The average occurrence for integers entered is " + averageFrequency);
            }
    }

Answer: You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
Comment: Wow we're totally histograms in my discrete class right now, that didn't even click.  The link on count-sorting was extremely helpful, thanks!
Comment: @obfuscater: I'm glad you are making this connection. You will soon enough realize that the math and theoretic classes you are taking will be a great asset for you as a programmer!
Answer: To calculate occurences, you can do something like this:
 for(int eachInteger : input) {
      occurrenceArray[eachInteger]++;
 }

This will replace your while loop.
Comment: Dont feed answers to questions tagged homewotk
Comment: I had not thought of incrementing array elements that way, (have only been on arrays for a week).  Definitely easier on the eyes than what I had!


Setting position of the header text right above the other content in CSS

Question: This issue is related to the topic mentioned here.
I managed to fix my previous CSS code to get the effect of having text aligned to the middle of the picture, but now I would like to add a header to the text. My problem is that I have troubles with aligning the header, currently it looks like this: https://jsfiddle.net/u8db2j75/ , but I would like to achieve the effect like this: https://i.stack.imgur.com/PRTyh.png where the header text is right above the normal text. I don't know why in my solution there's this huge gap between the header and the text. Could you help me with my issue? My current css code is as follows:
* {
  box-sizing: border-box;
}
.container {
  width: 100%;
  max-width: 60rem;
  /* 960 */
  margin: 0 auto;
}
.item {
  width: 100%;
  overflow: hidden;
  margin-bottom: 5rem;
  display:table;
  /* 80 */
}
.item__img,
.item__info {
  width: 50%;
  display:table-cell;
  vertical-align:middle;
}
.item__img {} .item__img .img-map {
  width: 95%;
  height: 18.750rem;
  /* 300 */
}
.item__img img {
  width: 95%;
  height: 18.750rem;
  /* 300 */
}
h2 {
    font-weight: normal;
    font-size: 4rem;
    /* 64 */
    text-align: left;
}

and current html code is this:

HEADER

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac sodales orci. Praesent sit amet consequat purus. Praesent lobortis mi quis rutrum fringilla. Phasellus velit arcu, ultricies vestibulum varius sed, convallis ut eros. Vestibulum
        vel congue felis, ut lacinia tellus. Integer ullamcorper gravida ligula non convallis. Ut suscipit vulputate erat eu porttitor. Morbi sagittis vulputate bibendum. Aliquam ultricies finibus tortor, a elementum nisl aliquet at. In sed dui id mauris
        rutrum ornare.

Thanks!
Answer: The answer to this lies in the answer I gave on the previous question. There's spacing because the browser applies it's own stylesheet.
Here's what firefox adds:
h2, *:-moz-any(article, aside, nav, section) h1 {
    display: block;
    font-size: 1.5em;
    font-weight: bold;
    margin: 0.83em 0;
}

You just need to add a style that overwrites the margin.
As I mentioned before, you can use a developer console either in Google Chrome, or by adding Firebug to Firefox. This will allow you to see what styles are being applied to which elements on the page, just by pressing F12.
Comment: Thanks, but am I not overwrite it by using my own stylesheet for h2:
`h2 {
    font-weight: normal;
    font-size: 4rem;
    /* 64 */
    text-align: left;
}`
? If not, what else should I overwrite here? Thanks!
Answer: You must reduce the bottom margin of h2 (53px) and the top margin of  (16px)
h2 {
    font-weight: normal;
    font-size: 4rem;
    /* 64 */
    text-align: left;
margin-bottom: 0px;
}
p{
    margin-top: 2px;
}

Answer: Inspect the code and you'll see a margin applied to your
 :

This is caused by default CSS value.
It is very recommended you add * {padding: 0; margin: 0;} to disable default padding/margin on every element, then you'll be able to add your own margins/paddings on whatever you want.
Answer: When you have a heading followed by a paragraph, there are (generally) no more than 4 style declarations that create a visible vertical gap between the heading and the paragraph. These 4 style declarations are (in order):
1) The padding-bottom of the heading;
2) The margin-bottom of the heading;
3) The margin-top of the paragraph;
4) The padding-top of the paragraph;
With more advanced layouts, declarations like line-height will also play a role, but we don't need to worry about that for now.
Therefore, if you want to ensure that there is zero visible gap between the second-level heading and the paragraph which follows it, you might declare the following rules:
h2 {
margin-bottom: 0;
padding-bottom: 0;
}

p {
margin-top: 0;
padding-top: 0;
}

Of course, if we leave it there, the style rules for the paragraph above will apply to all paragraphs. If we want these style rules to apply only to paragraphs which immediately follow an
, then we can make the styles above slightly more explicit by declaring:
h2 {
margin-bottom: 0;
padding-bottom: 0;
}

h2 + p {
margin-top: 0;
padding-top: 0;
}

The + selector above indicates that the rules only apply to the element after the selector when it is the sibling which immediately follows the element before the selector.
Now that you have zero visible gap between the
 and the
, you can tweak your margins and paddings as appropriate.


Bootstrap Datepicker not clearing for date range

Question: I'm using this datepicker (version 1.6.1) in a project. I have a button that clears all inputs in a form and according to the documentation, all I need to do is
$(".selector").datepicker("clearDates");

This is working fine for a single datepicker field but it doesn't work for a date-range.

$(document).ready(function() {
  $(".date").datepicker({
    todayBtn: "linked",
    daysOfWeekHighlighted: "0,6",
    autoclose: true,
    todayHighlight: true,
    orientation: "bottom",
    format: "mm/dd/yyyy"
  });

  $(document).on("click", "button", function(e) {
    e.preventDefault();

    $(".date").datepicker("clearDates");
  })
});
body {
  padding: 20px;
}

.input-group {
  margin-bottom: 10px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.1/css/bootstrap-datepicker.min.css" rel="stylesheet" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <input name='single' class='single basic-input form-control' placeholder='MM/DD/YYYY' autocomplete='off'>

  <input name='start' class='start basic-input form-control' placeholder='MM/DD/YYYY' autocomplete='off'>

to

  <input name='end' class='end basic-input form-control' placeholder='MM/DD/YYYY' autocomplete='off'>

<button id='clear-params' type='button' class='btn btn-warning btn-block' aria-label='Clear'>
  Clear
</button>

Here's a Fiddle if you prefer to debug over there.
Answer: Because you were missing selector classes in daterange

$(document).ready(function() {
  $(".date").datepicker({
    todayBtn: "linked",
    daysOfWeekHighlighted: "0,6",
    autoclose: true,
    todayHighlight: true,
    orientation: "bottom",
    format: "mm/dd/yyyy"
  });

  $(document).on("click", "button", function(e) {
    e.preventDefault();

    $(".dateselector").datepicker("clearDates");
  })
});
body {
  padding: 20px;
}

.input-group {
  margin-bottom: 10px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.1/css/bootstrap-datepicker.min.css" rel="stylesheet" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <input name='single' class='single basic-input form-control dateselector' placeholder='MM/DD/YYYY' autocomplete='off'>

  <input name='start' class='start basic-input form-control dateselector' placeholder='MM/DD/YYYY' autocomplete='off'>

to

  <input name='end' class='end basic-input form-control dateselector' placeholder='MM/DD/YYYY' autocomplete='off'>

<button id='clear-params' type='button' class='btn btn-warning btn-block' aria-label='Clear'>
  Clear
</button>
Comment: nope.. you are unnecessarily running it on divs.. If you need you can some common class on inputs
Comment: @uom-pgregorio check updated answer, used common class `dateselector`
Comment: Yes I prefer this version. Thanks!
Comment: Darn. All the while I thought the class has to be on the parent element and not the input itself. Thanks!
Comment: Your edit actually messed it up. The two date ranges are no longer linked if you remove the `date` class on the parent element. Your first answer was the correct one. You have to have the `.date` on the parent and both inputs.
Comment: yeah.. was just experimenting
Comment: @uom-pgregorio check updated answer, calling datepicker only on intended elements. lets leave `date` to be used by plugin.
Comment: I would say a better solution would be to do `$(".date input").datepicker("clearDates");`. It's just so when I decide to add another date field I won't have to modify the JS file.


Convergence of a sequence

Question: The sequence $a_n=\frac{1}{n^2}+\frac{1}{(n+1)^2}+.....\frac{1}{(2n)^2}$
1.converges to $0$.
2.converges to $1/2$.
3.converges to $1/4$.
4.Does not converge.
I think 2 is correct answer because $a_n=\sum_{k=1}^n \frac{1}{(n+k)^2}=\sum_{k=1}^n\frac{1}{(n^2)(1+k/n)^2}$$\rightarrow \int_1^2 \frac{1}{x^2}dx=1/2$.
Is it correct?
Comment: Isn't $\sum_{n=1}^\infty 1/n^2$ a convergent series?
Comment: It's not correct, the Riemann sum you seem to have in mind would be $$\sum_{k=1}^n\frac{1}{n\,(1+k/n)^2}.$$ Moreover, your $a_n$ is the sum of $n+1$ terms $\le 1/n^2$, so it must clearly converge to $0$.
Comment: You have $n+1$ positive terms, the largest of them being $\frac{1}{n^2}$. Their sum is positive and bounded by $\frac{n+1}{2n^2}$, hence the first option is obviously the correct one. There is no need for Riemann sums.
Answer: Let $s_m:=\sum_{k=1}^m \frac{1}{k^2}$. Then $s_m \to \pi^2/6$ for $m \to \infty$. Hence
$a_n=s_{2n}-s_{n-1} \to 0$ for $n \to \infty$
Comment: I think it's worth mentioning that it isn't really important for the problem to know what exactly $s_m$ converges to, just that it converges by using a standard convergence test.
Comment: Thanks everyone for correcting me.

Convergence of a sequence


Number of H-free graphs on n vertices

Question: I'd like to get an estimate on the number of $H$-free graphs, i.e. graphs in which no set of $|V(H)|$ vertices induces a copy of $H$. There are results on this, but I have some problems in interpreting the probabilistic arguments.
For simplicity, let $H = K_3$, a triangle.
Let $G$ be a random graph on $n$ vertices in which each edge appears with probability $1/2$.
From this paper, we have that $Pr[G$ is $H$-free$] \leq e^{-c n^3/8}$ for some constant $c$ (see abstract, put $p = 1/2$ and $H = K_3$).
This probability seems very low, and I must be misinterpreting something.
Here's my problem.
Let $f(n)$ be the number of $H$-free graphs on $n$ vertices.
Then since $G$ is equally likely to be any graph on $n$ vertices,
$$Pr[G\mbox{ is }H\mbox{-free}] = f(n)/2^{{n \choose 2}}$$
i.e. the number of $H$-free graphs divided by the total number of graphs.
But
$$
f(n)/2^{{n \choose 2}} = Pr[G\mbox{ is }H\mbox{-free}] \leq e^{-c n^3/8}
$$
implies
$$
f(n) \leq 2^{n \choose 2}e^{-c n^3/8} < 1
$$
for large enough $n$.
Hence there are no triangle-free graphs.
Where is the mistake?
Answer: The mistake occurs in the application of their theorem. You are right that any probability below $\frac{1}{2^{{n \choose 2}}}$ must be zero. But per their abstract, $M=n^2 p$ rather than $m=n^3 p^3$.

Number of H-free graphs on n vertices


Dúvida sobre tipos genéricos em TypeScript

Question: Estou estudando atualmente o TypeORM, e queria criar um controller genérico, pois sempre serão as mesmas operações CRUD. Sei que posso resolver com soluções nativas do TypeORM, como por exemplo o getRepository(), inclusive já até resolvi, porém agora quero tirar essa dúvida que persiste...
Então, no modo que tentei anteriormente, minhas entidades estão estendendo a classe BaseEntity, para poder ter acesso ao método getRepository() diretamente na classe. Assim:
export abstract class AbstractEntity extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({default: true})
    ativo: boolean;

    @CreateDateColumn()
    createdAt: string;

    @UpdateDateColumn({ type: "timestamp" })
    updatedAt: number;
}

E essa classe somente para exemplificar:
export class Pessoa extends AbstractEntity {
    @Column()
    nome: string;
}

Eu esperava criar um controller genérico mais ou menos assim:
class GenericController<T extends BaseEntity> {
        async getAll(request: Request, response: Response, nextFunction: NextFunction) {
            return await T.getRepository().find();
        }
    }

Para utilizar assim:
export default class PessoaRoute {
    pessoaController = new GenericController<Pessoa>()

    constructor() {
        this.initializeRoutes();
    }

    initializeRoutes() {
        this.router.get('/', this.pessoaController.getAll);
    }
}

O problema que tenho é que no GenericController não tenho acesso aos métodos que preciso por meio do T, nem sequer ele é reconhecido como existente no TypeScript, isso naquele modo em que pretendo usar: T.getRepository().
Li um pouco na documentação do TypeScript mas não compreendi o motivo de isso não ter dado certo.
Answer: O problema que você está enfrentando resume-se em: o genérico nunca é um valor, mas sim um tipo. Desse modo, você não pode usá-lo como um valor.
Veja, no seu código, você está fazendo isso:

return await T.getRepository().find();

Percebe? Você está tratando o tipo genérico T como se fosse um valor, o que ele não é.
Desse modo, o que você precisa fazer é aceitar o objeto Pessoa como argumento da classe (provavelmente no construtor). Algo assim:
class GenericController<T extends Entity> {
  constructor(private model: T) { }

  async getAll(/* Seus parâmetros aqui... */) {
    return this.model.getRepository().find();
  }
}

Note que agora estamos usando this.model, que é um valor com o tipo T.
Em seguida, para usar, basta fazer isso:
export default class PessoaRoute {
  pessoaController = new GenericController(Pessoa);

  // ...
}

Note que nem é necessário passar o genérico explicitamente em GenericController, uma vez que o TypeScript irá inferir o tipo automaticamente.

Não tem muito a ver com a pergunta, mas perceba que eu removi o await do return await. Naquela situação, o return await é alto redundante. O próprio async naquela função também não é necessário, mas para torná-la explicitamente assíncrona, é uma boa prática deixá-lo lá. :)


How to count recurring identical values in a Pandas Series

Question: I have a Pandas Series with True/False values, and I need to count how often a value occus that is identical with the previous value.
Whenever the value changes, the  counting should restart at 1.
pd.Series([True, False, False, False, True, True, False])

0     True        --> 1
1    False        --> 1
2    False        --> 2
3    False        --> 3
4     True        --> 1
5     True        --> 2
6    False        --> 1
dtype: bool

I tried various combinations of shift() and cumsum(), but without success.
Any hints?
Ale
Answer: You can create groups by consecutive values with compare shifted values and cumsum and use it for cumcount:
s = pd.Series([True, False, False, False, True, True, False])

s1 = s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1)
print (s1)
0    1
1    1
2    2
3    3
4    1
5    2
6    1
dtype: int64

Detail:
print (s.ne(s.shift()).cumsum())
0    1
1    2
2    2
3    2
4    3
5    3
6    4
dtype: int32

Another solution is count Trues and Falses separately and then sum outputs:
cm1 = s.cumsum()
s1 = cm1-cm1.where(~s).ffill().fillna(0)
cm2 = (~s).cumsum()
s2 = cm2-cm2.where(s).ffill().fillna(0)
s3 = s1.add(s2).astype(int)
print (s3)
0    1
1    1
2    2
3    3
4    1
5    2
6    1
dtype: int32

Detail:
print (s1)
0    1.0
1    0.0
2    0.0
3    0.0
4    1.0
5    2.0
6    0.0
dtype: float64

print (s2)
0    0.0
1    1.0
2    2.0
3    3.0
4    0.0
5    0.0
6    1.0
dtype: float64

Timings:
np.random.seed(2018)
N = 1000000
s = pd.Series(np.random.choice([True, False], N))
#print (s)

def jez1(s):
    return s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1)

def jez2(s):
    cm1 = s.cumsum()
    s1 = cm1-cm1.where(~s).ffill().fillna(0)
    cm2 = (~s).cumsum()
    s2 = cm2-cm2.where(s).ffill().fillna(0)
    return s1.add(s2).astype(int)

print (jez1(s))
print (jez2(s))

In [173]: %timeit jez1(s)
1 loop, best of 3: 199 ms per loop

In [174]: %timeit jez2(s)
10 loops, best of 3: 92 ms per loop

Comment: I had exactly same, every word :)


Don't see a new branch after creation

Question: I have created a new branch and went with a browser to check if it was created but I don't see it.
$ git svn branch -n -m "Students line" student_line --destination branches
Copying https://<my_site>/svn at r294 to https://<my_site>/svn/branches/student_line...

Comment: Did you `push` to the appropriate remote repository?
Comment: "https:///svn" looks suspicious, does your SVN repository layout support branches at all?
Answer: Note that the -n switch is a synonym for --dry-run:

-n
--dry-run
This can be used with the dcommit, rebase, branch and tag commands.
For dcommit, print out the series of git arguments that would show which diffs would be committed to SVN.
For rebase, display the local branch associated with the upstream svn repository associated with the current branch and the URL of svn repository that will be fetched from.
For branch and tag, display the urls that will be used for copying when creating the branch or tag.

Remove the -n and do it for real.
In general, to sync with Subversion, make sure you have a clean branch, and then update git's view by running two commands:
$ git svn fetch
$ git svn rebase

Don't see a new branch after creation


Upperbound of Kullback-Leibler between marginals

Question: I want to know if for every pair of $p(x, y)$ and $q(x, y)$ the following inequality
$$
\int_X p(x) \log \frac{p(x)}{q(x)} dx \leq \int_X\int_Y p(x, y) \log \frac{p(x, y)}{q(x, y)}dxdy
$$
is valid.
I tried unsuccessfully to use Jensen's and Gibbs' inequalities.
Comment: Is $p(x)$ defined as $\int_Y p(x,y) \,dy$?
Comment: Yes, it is. I think I found the solution. I posted it as an answer.
Answer: I think I found the solution.
$$
p(x)\log\frac{p(x)}{q(x)} \leq \int_Yp(x,y)\log\frac{p(x,y)}{q(x,y)}dy
$$
implies
$$
\int_X p(x)\log\frac{p(x)}{q(x)}dx \leq \int_X \int_Yp(x,y)\log\frac{p(x,y)}{q(x,y)}dydx
$$.
Therefore,
$$
\int_Y p(x, y) \log \frac{p(x,y)}{q(x,y)}dy \\
= p(x) \int_Y p(y | x) \log \frac{p(x,y)}{q(x,y)}dy \\
= p(x) \int_Y p(y | x) \log \frac{p(y|x)p(x)}{q(y|x)q(x)}dy \\
= p(x) \int_Y p(y | x) \bigg(\log \frac{p(y|x)}{q(y|x)} + \log \frac{p(x)}{q(x)}\bigg)dy \\
= p(x) \int_Y p(y | x)\log \frac{p(y|x)}{q(y|x)}dy  + p(x) \int_Y p(y | x) dy \log \frac{p(x)}{q(x)} \\
= p(x) \int_Y p(y | x)\log \frac{p(y|x)}{q(y|x)}dy  + p(x) \log \frac{p(x)}{q(x)}.
$$
since
$$
p(x)\int_Y p(y | x)\log \frac{p(y|x)}{q(y|x)}dy
$$
is always positive, then
$$
p(x) \log \frac{p(x)}{q(x)} \leq \int_Y p(x, y) \log \frac{p(x,y)}{q(x,y)}dy
$$
which implies, as already mentioned,
$$
\int_X p(x)\log\frac{p(x)}{q(x)}dx \leq \int_X \int_Yp(x,y)\log\frac{p(x,y)}dx{q(x,y)}dy.
$$


Is it possible to create stacked bar charts in views?

Question: I'm using the Charts module with hightcharts to create charts in views, but I'm unable to create stacked one's.
Is this possible in views? Or is there any way I can override it with a custom module to achieve the same result?
Here is an example of what I need.
Also, my view:
$view = new view();
$view->name = 'stackedchart';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'StackedChart';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'My Stacked Chart';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'views_bootstrap_table_plugin_style';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'field_x_qc_testset',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'field_x_qc_week' => 'field_x_qc_week',
  'field_x_qc_status' => 'field_x_qc_status',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'field_x_qc_week' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_x_qc_status' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['bootstrap_styles'] = array(
  'striped' => 0,
  'bordered' => 0,
  'hover' => 0,
  'condensed' => 0,
);
/* Field: Content: x_qc_week */
$handler->display->display_options['fields']['field_x_qc_week']['id'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['table'] = 'field_data_field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['field'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['label'] = 'Week';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'xreport_qc' => 'xreport_qc',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_2');
$handler->display->display_options['defaults']['group_by'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['library'] = 'highcharts';
$handler->display->display_options['style_options']['type'] = 'column';
$handler->display->display_options['style_options']['label_field'] = 'field_x_qc_week';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_x_qc_status' => 'field_x_qc_status',
  'field_x_qc_week' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_x_qc_week' => '#2f7ed8',
  'field_x_qc_status' => '#0d233a',
);
$handler->display->display_options['style_options']['data_labels'] = 'TRUE';
$handler->display->display_options['style_options']['tooltips'] = 'TRUE';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: x_qc_week */
$handler->display->display_options['fields']['field_x_qc_week']['id'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['table'] = 'field_data_field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['field'] = 'field_x_qc_week';
$handler->display->display_options['fields']['field_x_qc_week']['label'] = 'Week';
/* Field: Content: x_qc_status */
$handler->display->display_options['fields']['field_x_qc_status']['id'] = 'field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['table'] = 'field_data_field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['field'] = 'field_x_qc_status';
$handler->display->display_options['fields']['field_x_qc_status']['group_type'] = 'count';
$handler->display->display_options['fields']['field_x_qc_status']['separator'] = ', ';
$handler->display->display_options['defaults']['sorts'] = FALSE;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'xreport_qc' => 'xreport_qc',
);
$handler->display->display_options['path'] = 'stackedchart';

If it can't be made with views, doing it with a custom module using EntityFieldQuery is also a good solution. My only issue is how to show the data in different x-axis values (field value) not knowing all the values of that field.
EDIT: Tried Pierre suggestion. dsm is outputing the name of the chart and I use it as $chart_id. No stack is produced in the chart.
The fields I have are week and status. I have multiple nodes, with different weeks and status and I need to stack the status for each week.
Below is the chart WITHOUT stacking.
Comment: Pierre, I solved the problem. I already had a view with multiple displays. Each one was filtered by x_qc_status (like different 'Joe'). I was assuming that, with the chart_alter function I was able to do it with only one views page. So I recreated this with multiple displays + chart_alter and now the chart shows as I need. Many thanks for your support.
Answer: Option 1
Refer to the issue about Stacking column/bar charts for an example of how you can do this with a custom module. Comment #3 in it contains a sample like so:
<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

This should work for both Google Charts and Highcharts as the charting library (engine).
Option 2
Your x_qc_status is like the equivalent of "Joe" in the sample you referred to. But you don't have any equivalent of at least "John" (and maybe also "Jane")? In other words: I think you only have 1 dataset to be shown in your "stacked" bar chart, and that your problem is not in the chart, but in the related "view" for which you want to create a "stacked" chart.
Therefor try the "bonus tip" mentioned in Steps to create charts using the views UI. That may help to refine your view before actually creating the chart.
Comment: Pierre, that doesn't work. I already tried.
Comment: Can you enhance your question to explain the "that doesn't work"? That might help to get you going.
Comment: Sorry Pierre, it was not well explained. I edited and added more information. Hope it's enought to understand what's the issue. And thanks again for the support.


Can Relative Risk mislead us when choosing predictors for a logistic model?

Question: My friend taught me to use Relative Risk as a guide to check if my coefficients make sense. For example, I have a propensity to default model, where the variable fl_default is equal to 1 if the individual defaulted and equal to zero if he didn't default. I also have the region where individuals belong: A, B, C, D and E - and other variables. In the figure below, I have the number of people that defaulted in each region and their relative risk, and what I understand is that people in region A, B and D are good customers, they have more propensity to pay.

However, if I run a logistic regression and the coefficient for the predictor REGION is the opposite of this Relative Risk, should I treat this variable (make some modification) or it is possible that the coefficient gives a different direction than the relative risk? What could be happening with my model?
Comment: A more straightforward diagnostic for the sign of the model coefficient is to compare it to the sign of a pairwise, spearman correlation. If they aren't the same, then that can suggest an underlying issue with collinearity.
Answer: This is not a direct answer to your question but I suspect it might solve some issues for you.
A relative risk compares two groups so in your situation you could compare the risk of defaulting in group A versus group D. The risk in group A is $\frac{86}{86 + 179}$ and in group D is $\frac{240}{240 + 268}$. The risk ratio is thus the ratio of these two quantities
$$\frac{\frac{86}{86 + 179}}{\frac{240}{240 + 268}}$$
If when you work them out correctly you still get an issue then perhaps better to post a new question.


Como tratar exceções de duplicidade em constraint unique?

Question: Fala devs, tudo bem?
Qual a melhor forma de lidar com erros de duplicidade quando tenta criar campo com constraint unique?
Apenas deixo a exceção acontecer? Ou eu um findByAlgumCampo e se já existir eu não faço o save(..) ?
Comment: sem mais informações do cenário fica difícil responder, vai ser "baseada em opiniões". Se isso for acontecer raramente, já que tem a constraint no banco, deixe dar erro, coloque o código num try/catch e pronto. Se acontecer com frequência pode fazer mais sentido validar antes. A melhor estratégia depende da query, se a tabela é pequena e pode usar cache, muitas variáveis. A princípio deixe dar erro, trate e use um log, dependendo dos resultados (muitos erros, etc) pode mudar no futuro
Comment: a ideia era deixar genérico porque eu queria saber se havia algum padrão a ser seguido.  porém, mais tarde, descobri que a exceção é mais genérica do que eu gostaria e exige a mesma quantidade de código (se não mais) para identificar que foi do tipo 'duplicidade'.
Comment: em geral os providers de acesso a banco de dados retornam erros mais específicos em casos de constraint, olhe bem isso. Validar antes também significa fazer duas operações ao no banco de dados, select e insert. Como eu comenti na pergunta, tem analisar bem o seu caso, mas o mais simples é deixar dar exception e tratar
Answer: Opa, tudo bem e por ai?
Então, tudo depende da regra de negócio da sua aplicação. Mas eu acredito que se você fizer o find antes e não executar o save(...), você terá que informar algum erro para o usuário dizendo que o dado não foi salvo por já existir.
Então nesse sentido, acredito que é melhor deixar a exception acontecer, mas tratá-la no momento de exibir para o usuário (ou retornar na API).
No caso da API, é importante que o erro de banco não seja retornado diretamente, mas que você trate ele, e retorne uma mensagem mais "genérica":
{
    "erro": "O registro já existe"
}

Mas como falei ali, tudo depende da regra de negócio da aplicação, e do cenário em questão.
Algo assim.


Não consigo deletar chave no dbm

Question: Fiz um programinha básico para armazenar alguns dados e estou com problemas caso o usuário escolha a opção de deletar alguma chave do dicionário armazenado. A função que apaga os dados no meu programa é essa:
def EraseData(name):
'''
Apaga uma chave do dicionário do banco de dados.
'''
db = dbm.open('data.db', 'c')
del db[name]
db.close()

Quando vou pesquisar as entradas no meu banco de dados vejo que NADA foi apagado. Simplesmente não funciona.
Esse é o link de todo o meu código do GIT:https://github.com/JeffersonCarvalh0/Armazenamento-de-dados/blob/master/armazenamento.py
Comment: Acho que aqui pode ajudar você. http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
Comment: Mas eu não quero manter o banco de dados e apagar de uma cópia, eu quero mesmo é mudá-lo. No entanto, mesmo usando o `del` eu não consigo. Percebi que pelo modo interativo, quando eu executo exatamente as mesmas linhas que tenho na função, eu consigo apagar a chave, mas pela função não funciona.
Comment: Então, você precisa detalhar mais o seu erro. A função está correta, funciona perfeitamente. Seu programa, entretanto, tem alguns erros não funcionando devidamente. Arrumei os erros e tudo funcionou perfeitamente. Tem certeza que o problema é esse que você expôs?
Answer: Testei aqui, e usando direto no modo interativo funciona o del  (apesar de a documentçção desse módulo ser bem fraquinha e nem mencionar o del e nem ele aparecer no dir do objeto dbm).
A minha hipótese é a seguinte: você tem essa funão EraseData e nela você abre, modifica e fecha o banco - no entanto, acredito que se o mesmo banco estiver aberto enquanto você faz essas açoes, pode ser que quando ele feche a outra cópia do banco que está aberta as chaves que existam lá é que fiquem valendo. Você tem o banco aberto numa variável no contexto que chama o EraseData (ou em outra thread/contexto qualquer?)
Eu não acredito que esse módulo vá funcionar bem abrindo mais de uma conexão ao mesmo tempo ao mesmo arquivo - nem que tenha sido pensado para funcionar assim: minha sugestão é abrir esse banco no início do programa, e só fecha-lo na saída. (use uma cláusula try...finally para garantir que a função close seja chamada - e, ou passe a instância do banco para todas as funções que o acessam, ou crie uma classe em que um dos atributos é a instância do banco - e promova todas as funções para métodos dessa classe, ou simplesmente deixe um avariável global com a instância do banco  (não é tão ruim em Python como em C ou outras linguagens, porque variáves "globais" não são realmente "globais" - são variáveis de módulo com vigência apenas no namespace daquele módulo)
Answer: Como eu disse, você precisa detalhar mais o seu erro. A função que você criou funciona perfeitamente, mas, no entanto, há alguns errinhos no seu programa que a impedem de funcionar.
Primeiro, erros de sintaxe, na função CheckRg, endente o if corretamente.
Segundo, na função ShowList, está dando que db não é iterável. Sendo assim, itere sobre as chaves do banco:
for key in db.keys():
    ...

Por fim, a parte que de fato impede a função EraseData de funcionar é o levantamento da exceção FileAlreadyExists na função SearchData. A exceção está sendo levantada antes de se fechar a conexão com o banco de dados. Isso impede que a função EraseData abra uma nova conexão (gerando uma nova exceção) e delete definitivamente uma entrada.
Logo:
def SearchData(nome):
    db = dbm.open('data.db', 'c')
    if name in db:
        db.close()
        raise FileAlreadyExists

Depois que isso foi feito, a função funciona perfeitamente. Caso contrário, precisamos de mais detalhes da execução do seu programa.
Comment: Ah, agora sim... quanto aos erros de sintaxe, não sei de onde saíram, pois ontem quando criei esse tópico, o código estava sem erros (deve ter sido devido a alguma confusão que eu fiz enquanto tentava passar esse código pro `GIT`, pois ainda estou aprendendo a mexer nele).
    Quanto à minha função `ShowList`, aqui ela funciona perfeitamente.
    Por último, eu realmente não tinha visto esse problema na função `SearchData`. Fiz a correção sugerida e agora o programa funciona sem problemas. Muito obrigado.

Não consigo deletar chave no dbm


Imagem em ListTile - Flutter

Question: Não estou conseguindo deixar minha imagem na minha ListTile, quando tento dimensionar a mesma só vai para horizontal e nunca na vertical, exemplo:

Segue código, estou tentando dimensionar com a propriedade radius:
ListView.separated(
    separatorBuilder: (context,index) => Divider(
      color: Colors.black),
  itemCount: _professionals.length,
  itemBuilder: (context,index){
    return
    ListTile(
      contentPadding: EdgeInsets.all(15.0),
      leading:
      CircleAvatar(
        backgroundImage: AssetImage("images/perfil_anhan.jpg"),
        radius: 70,
      ),
      title: (Text(getName(_professionals[index]))),

      ...

Como poderia deixar ela proporcional?
Comment: Tente utilizar o atributo `child` do `CircleAvatar` ao invés do `backgroundImage`. Dentro do `child` utilize o `Image.asset()` e nele preencha a propriedade `fit` que é utilizada para ajustar as imagens dentro dos seus recipientes. Exemplo: `CircleAvatar(child: Image.asset("name", fit: BoxFit.contain,),);`
Comment: Olá Matheus, não consegui resolver desta forma, porém me deu uma luz e consegui resolver de outra maneira. Já vou colocar abaixo, obrigado!
Comment: Állan, nenhuma resposta atendeu sua necessidade? caso não, explique melhor o que precisa para que possamos resolver.
Answer: O ideal seria o CircleAvatar, em vista da imagem que passou, e como já comentaram.
Exemplo:
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.brown.shade800,
            child: Text('AH'),
          ),
          title: Text('Fulano'),
          subtitle: Text('da Silva'),
        ),
        ListTile(
          leading: CircleAvatar(
            backgroundImage: NetworkImage('https://imagens.canaltech.com.br/empresas/690.400.jpg'),
          ),
          title: Text('Ciclano'),
          subtitle: Text('de Jesus'),
        ),
      ],
    );
  }
}

1º usando cor no fundo e texto.
2º usando imagem.

Resultado

Documentação oficial: CircleAvatar
Answer: Galera, resolvi usando a propriedade child, e dentro dele um Container com borderRadius para definir o tamanho.
Segue abaixo solução:
                child: Container(
                    width: 100.0,
                    height: 100.0,
                    decoration: BoxDecoration(
                        color: Colors.red,
                        image: DecorationImage(
                            image: AssetImage('images/hacker.jpeg'),
                            fit: BoxFit.cover),
                        borderRadius:
                            BorderRadius.all(Radius.circular(75.0)),
                        boxShadow: [
                          BoxShadow(blurRadius: 7.0, color: Colors.black)
                        ]),
                  ),

Imagem em ListTile - Flutter


Look up next date a class is taught after current date, referencing another sheet

Question: I'm trying to create a spreadsheet that lists a series of unique class names, and then checks a schedule spreadsheet for the NEXT time that class is taught.
Here is a sample sheet I'm looking to make, with the highlighted cells being the ones that need formulas. And here is a second sheet with the data. So the formula should:

Use the "Tab" column of the first spreadsheet to point towards the
appropriate tab of the destination sheet.
Some kind of Index-Match for the class name?
(and this is the hard one) Take today's date into account to find the next time a given session is taught.

Column D (for the NEXT next time the session is taught) should be just the same fomula as column C, but with the date in column C substituted for today's date.
The result should be a spreadsheet that lists each class and the next two times that class will be held.
Here's my best attempt at this, with B2 being the class name I'm trying to match, column A of the schedule sheet being my dates, and column B of the schedule sheet being my class names. I didn't attempt to make the "Tab 1" part driven by the formula:
=iferror(index((IMPORTRANGE("157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY","'Tab 1'!A1:A80")),(match(ArrayFormula($B2&today()),ArrayFormula(IMPORTRANGE("157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY","'Tab 1'!B1:B80")&(IMPORTRANGE("157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY","'Tab 1'!A1:A80"))),-1)),""))
That -1 at the end is supposed to return the smallest result that is greater than my class name concatenated with the current date. But while it works for some cells, it definitely doesn't work for others. What am I doing wrong?
Comment: Add some sample data and the expected result for each case.
Comment: Updated with sample data.
Comment: Please add a brief description of your search/research efforts and attempts to write the formulas you are looking for.
Comment: Updated with my janky formula.
Answer: In C2 and dragged down to suit:
=array_constrain(query({importrange("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=0","'Tab 1'!A1:B10");importrange("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=28833949","'Tab 2'!A2:B10");IMPORTRANGE("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=416018764","'Tab 3'!A2:B10")},"select Col1 where Col2 ='"&B2&"'limit 2 offset 1 ",0),1,1)

should return the dates you show as required (provided access is granted for the imports) for Next Taught, but the other column is a different question and you have not explained how 'today' fits in with a post dated December 3 where the results for 'Next Taught` precede that.
You might prefer to separate the above into what may be easier to understand and adapt:
Say in G1:
={
importrange("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=0","'Tab 1'!A1:B10");
importrange("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=28833949","'Tab 2'!A2:B10");
importrange("https://docs.google.com/spreadsheets/d/157E80WQaamKMRi6V4cnFWMMFMTEhdlfwALiqmsr0-JY/edit#gid=416018764","'Tab 3'!A2:B10")
}

then instead in C2 and copied down to suit:
=array_constrain(query(G:H,"select G where H ='"&B2&"'limit 2 offset 1 ",0),1,1)


RPG em turnos - Personagem e inimigo recebem o mesmo ataque

Question: Eu estou desenvolvendo um RPG em turnos e estou tendo problemas. O jogador e o inimigo são a mesma classe de objeto instanciada e eles possuem os métodos de atacar e receber dano. Contudo quando eu ataco ambos os personagens tem a vida subtraída.

Classe Atributos

class Atributos
{
    //ATRIBUTOS DA CLASSE

    public int vitalidade;
    public int armadura;
    public int forca;
    public int inteligencia;
    public int agilidade;
    public int sorte;

    //CONSTRUTORES

    public Atributos ()
    {
        this.vitalidade = 0;
        this.armadura = 0;
        this.forca = 0;
        this.inteligencia = 0;
        this.agilidade = 0;
        this.sorte = 0;
    }

    //SETTERS

    public void setVitalidade (int vitalidade)
    {
        this.vitalidade = vitalidade;
    }

    public void setArmadura (int armadura)
    {
        this.armadura = armadura;
    }

    public void setForca (int forca)
    {
        this.forca = forca;
    }

    public void setInteligencia (int inteligencia)
    {
        this.inteligencia = inteligencia;
    }

    public void setAgilidade (int agilidade)
    {
        this.agilidade = agilidade;
    }

    public void setSorte (int sorte)
    {
        this.sorte = sorte;
    }

    //GETTERS

    public int getVitalidade ()
    {
        return this.vitalidade;
    }

    public int getArmadura ()
    {
        return this.armadura;
    }

    public int getForca ()
    {
        return this.forca;
    }

    public int getInteligencia ()
    {
        return this.inteligencia;
    }

    public int getAgilidade ()
    {
        return this.agilidade;
    }

    public int getSorte ()
    {
        return this.sorte;
    }

}

Classe Personagem

import java.util.Random;

class Personagem extends Atributos
{

    //ATRIBUTOS

    public static String nome;
    public static String classe;
    public static int defesa;
    public static int critico;
    public static int danoMinimo;
    public static int danoMaximo;
    public static int healthPoints;
    public static int manaPoints;

    //CONSTRUTOR

    public Personagem ()
    {
        this.nome = "";
        this.classe = "Mago";
        this.vitalidade = 10;
        this.armadura = 10;
        this.forca = 10;
        this.inteligencia = 10;
        this.agilidade = 10;
        this.sorte = 10;
        this.defesa = 10 + this.armadura;
        this.critico = this.sorte / 100;
        this.healthPoints = 100;
        this.manaPoints = 100;
        this.danoMinimo = 10;
        this.danoMaximo = 20;
    }

    //SETTERS

    public void setNome (String nome)
    {
        this.nome = nome;
    }

    public void setClasse (String classe)
    {
        this.classe = classe;
    }

    public void setDefesa (int defesa)
    {
        this.defesa = defesa;
    }

    public void setCritico (int critico)
    {
        this.critico = critico;
    }

    public void setHealthPoints (int healthPoints)
    {
        this.healthPoints = healthPoints;
    }

    public void setManaPoints (int manaPoints)
    {
        this.manaPoints = manaPoints;
    }

    public void setDanoMinimo (int danoMinimo)
    {
        this.danoMinimo = danoMinimo;
    }

    public void setDanoMaximo (int danoMaximo)
    {
        this.danoMaximo = danoMaximo;
    }

    //GETTERS

    public String getNome ()
    {
        return this.nome;
    }

    public String getClasse ()
    {
        return this.classe;
    }

    public int getDefesa ()
    {
        return this.defesa;
    }

    public int getCritico ()
    {
        return this.critico;
    }

    public int getHealthPoints ()
    {
        return this.healthPoints;
    }

    public int getManaPoints ()
    {
        return this.manaPoints;
    }

    public int getDanoMinimo ()
    {
        return this.danoMinimo;
    }

    public int getDanoMaximo ()
    {
        return this.danoMaximo;
    }

    public void Ataque (Personagem inimigo)
    {
        Random rand = new Random();

        int ataque;

        ataque = rand.nextInt(this.danoMaximo) + this.danoMinimo;
        inimigo.healthPoints = inimigo.healthPoints - (ataque - inimigo.defesa);

    }

    public void recebeDano (Personagem inimigo ,int ataque)
    {
        this.healthPoints = ataque - defesa;

    }

}

Classe Principal

import java.util.Scanner;
 import java.util.Random;

class Partida
{
    static Scanner scanf = new Scanner(System.in);
    static Random  rand  = new Random();

    static Personagem jogador = new Personagem();
    static Personagem inimigo = new Personagem();

    public static void main(String[] args)
    {
        Introducao();
        telaPersonagem();
        chamaTurno();
        jogadorTurno();
        cpuTurno();
        vitoria();

    }

    public static void Introducao ()
    {
        System.out.println("SEJA BEM-VINDO A ARENA, GUERREIRO! DIGA-NOS SEU NOME: ");
        jogador.setNome("LUCAS");
        inimigo.setNome("LUCAS");

    }

    public static void telaPersonagem() // MOSTRA A TELA COM INFORMAÇÕES DOS PERSONAGENS
    {
        System.out.println("NOME: " + jogador.getNome() + "                     NOME:" + inimigo.getNome());
        System.out.println("HP: " + jogador.getHealthPoints() + "                                   HP: "  + inimigo.getHealthPoints());
        System.out.println("MP: " + jogador.getManaPoints() + "                             MP: "  + inimigo.getManaPoints());

    }

    public static void chamaTurno()
    {

        int jogadorAgi;
        int cpuAgi;

        do
        {

        jogadorAgi = rand.nextInt(1) + jogador.getAgilidade();
        cpuAgi = rand.nextInt(1) + inimigo.getAgilidade();

            if(jogadorAgi > cpuAgi)
            {
                jogadorTurno();

            } else
            {

            }

        } while(jogadorAgi != cpuAgi);

    }

    public static void jogadorTurno()
    {
        int acao;

        do
        {

            System.out.println("SEU TURNO");
            System.out.println("");
            System.out.println("Escolha uma acao");
            System.out.println("1 - Atacar");
            System.out.println("2 - Atacar forte");
            System.out.println("3 - Atacar FORTE MESMO");
            acao = scanf.nextInt();

            switch(acao)
            {
                case 1 :
                    jogador.Ataque(inimigo);
                    System.out.println("Ataque realizado com sucesso");
                    telaPersonagem();
                    chamaTurno();
                    break;

                default :
                    System.out.println("Digite um comando valido");
            }

        } while(jogador.healthPoints != 0 || jogador.healthPoints < 0);

    }

    public static void cpuTurno()
    {
        int acao;

        acao = rand.nextInt(1) + 3;

        System.out.println("TURNO INIMIGO");

        do
        {
            switch (acao)
            {
                case 1:
                    inimigo.Ataque(jogador);
                    System.out.println("Você e atacado com sucesso");
                    chamaTurno();
                    break;

                case 2:
                    inimigo.Ataque(jogador);
                    System.out.println("Você e atacado com sucesso");
                    chamaTurno();
                    break;

                case 3:
                    inimigo.Ataque(jogador);
                    System.out.println("Você e atacado com sucesso");
                    break;
            }
        } while(inimigo.healthPoints != 0 || inimigo.healthPoints <= 0);

    }

    public static void vitoria()
    {
        if(jogador.healthPoints == 0)
        {
            System.out.println("Voce perdeu!");
        }

        if(inimigo.healthPoints == 0)
        {
            System.out.println("Voce venceu!");
        }
    }

}

Alguém sabe o que estou fazendo de errado?
Comment: Por favor, apresente um **[mcve]** para que seja possivel testar o codigo,
Comment: Faça com que seus métodos recebam como parâmetro tanto um herói quanto um vilão, coloque-os dentro do `main` e remova o `static` dos atributos.
Comment: Ops! Perdão, não quis colocar o código todo por achar ele muito grande, desculpe-me. Aqui estão as três classes do código.
Answer: O problema da sua solução é que os atributos da sua classe Personagem são static. Atributos static são atributos da classe e não atributos dos objetos.
Remova o static que irá funcionar.
Comment: Muitíssimo obrigado!


Enviar mensagem após o click do botão submit

Question: Como faço para identificar com PHP se um botão submit foi clicado? e após o click quero enviar uma mensagem de confirmação de click!.
Detalhe tudo em PHP.!!!
Assim não está funcionando não
<form  method="POST">

    <input type="text" name="salario">

    <input type="text" name="bonificacao">

    <input type="submit" name="btn">
</form>

<?php

$btn = $_POST['btn'];

if(!$btn){

   echo " O botão foi clicado ";

}else{

}

Comment: Acredito que o problema seja no primeiro acesso  um warning de `undefined index` é gerado pois o `$_POST` ainda não existe um `isset()/empty()` deve resolver, para mais detalhes veja [Como saber se o form é enviado](https://pt.stackoverflow.com/a/89142/91) e [Quando é necessário utilizar o isset?](https://pt.stackoverflow.com/q/58355/91)
Comment: Não funciona nem quando você pressiona o botão? Logo que carrega a página a primeira vez é esperado dar errado, já que você estará fazendo uma requisição GET e recuperando valores POST que não existem. Aliás, por quê a condição no `if` é `!$btn`?
Comment: Não da certo não, Tem hora que ja aparece a mensagem sem ser clicado
Answer: TESTE
if (isset($_POST['btn'])){
   echo " O botão foi clicado ";
}else{
   echo "esperando botão ser clicado";
}

Answer: Você deve usar um meio que se relacione com o POST para verificar se o botão foi clicado, veja o exemplo:
<form action="" method="post">
<input type="text" name="salario">

<input type="text" name="bonificacao">

<input type="hidden" name="validar" value="989">
<input type="submit" name="go" value="Vai" />
</form>

<?php
if(isset($_POST['validar'])){
$valida = $_POST['validar'];
if($valida == 989){
echo 'Clicado';
}
}
?>

Answer: Tenta tirar a exclamação da sua condição, você está negando a condição.
Se não der certo tente assim. Coloca o value no submit:
<form  method="POST">
  <input type="text" name="salario">

  <input type="text" name="bonificacao">

  <input type="submit" name="btn" value="Botão">
</form>

Sempre que você submeter ele vai mandar o submit, dai você verifica se está passando o valor:
<?php
  if (isset($_POST['btn']) and ($_POST['btn'] <> "")) {
    echo " O botão foi clicado ";
  } else { }

Comment: Cara, os códigos estão no mesmo arquivo?
Comment: Não deu certo não! assim a mensagem já vem impressa na tela
Comment: Quero mostrar a mensagem somente após o click!!! mais quero fazer isso com PHP
Comment: Modifiquei o código, dá uma olhada se funciona. Fiz uns testes aqui e funcionou.


force clang to use llvm instead of gcc in linux

Question: How can I make use of llvm as clang backend to compile C++ files without using gcc as clang's backend?
I am pretty sure clang is using gcc because
$ clang++ --version
clang version 6.0.1 (tags/RELEASE_601/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/bin

it uses gnu as target instead of llvm. My llvm-config output:
$ llvm-config --version --targets-built
6.0.1
X86

I built both clang and llvm from source using standard options for my build target(X86).
EDIT: I think it is using gcc as backend because this code produces error in online ide but works on my machine with clang++ and g++. Code relies on fact that gcc has implementation of policy based data structures which are not part of standard.
Comment: Why do you think it is using `GCC` as its backend?
Comment: Are you worried about the "Target"? Then don't be, it's the target *platform* (processor and operating system) which is almost universally *always* "linux-gnu" for Linux.
Comment: On `Linux` clang uses `GCC` Standard Libraries `libstdc++`. But it doesn't use the compiler.
Comment: I am new to this so I mentioned everything I thought would be useful to find help!
Comment: @Galik Because when I used `-H` option it included all the path as `g++` includes. And also all policy based data structure which are gcc's implementation shouldn't work in llvm backend (I suppose).
Answer: The problem is in the interpretation of the data. The target that clang refers to has to do with the platform for which you are generating code.

x86_64 This is a 64 bit processor compatible with Intel/and
unknown I'm uncertain about this one, though I believe it specifies more detail about the processor, which ain't available
linux You are using a Linux kernel/operation system
gnu The object structure should follow the gnu standards, I believe this directly maps on ELF

This will be different if you use BSD or windows as OS, or when your processor is an ARM, Intel 32 bit, Spark ...
The only moment you should be worrying about the target is when you are cross compiling. In other words, if the computer on which you are running the compiler has other requirements for the executable structure than the machine on which you will be running it.
PS: Clang always uses LLVM for it's IR. ignoring the deprecated Clang+C2, it always uses the LLVM optimizer and code generator.
Comment: @madhur4127 if installed through a package manager, clang has a dependency on libllvm
Comment: but if clang uses only LLVM tools then how is it possible to run clang without llvm installed? or does clang come with required llvm tools for it to compile without gcc backend?
Comment: AFAIK the `unknown` part is related to the vendor. As a small reference, see here : https://wiki.osdev.org/Target_Triplet .


Analogue to Fixed Point Theorem for Compact metric spaces

Question: If $\omega:H \rightarrow H$ (into) is continuous and $H$ is compact, does  $\omega$ fix any of its subsets other than the empty set?
Comment: related: http://math.stackexchange.com/questions/127020/fixed-set-property
Answer: the proof I learned from Henno Brandsma's answer: Let $X$ be compact Hausdorff (no metric is needed), and define $A_0 = X$, $A_{n+1} = f[A_n]$; then all $A_n$ are compact non-empty, and the $A_n$ are decreasing. Try to show that $A = \cap_n A_n$, which is also compact and non-empty, satisfies $f[A] = A$.
Another non-constructive way to show this is to consider the poset $\mathcal{P} = \{ A \subset X \mid A, \mbox{closed, non-empty and } f[A] \subset A \}$, ordered under reverse inclusion. Then an upper bound for a chain from $\mathcal{P}$ is the (non-empty) intersection, and a maximal element (by Zorn one exists) is a set $A$ with $f[A] = A$.
Comment: $A$ will be all of $X$ whenever $f$ is surjective.
Comment: do you know how to prove any metric space is hausdorff?
Comment: That's a good proof, but I don't need X (or H) Hausdorff.
Comment: I assume you are in $\mathbb{R}$ and you already said your H is compact, do you know $\mathbb{R}$  is hausdorff space?
Comment: H is simply a metric space; no assumptions of R.
Comment: aha thats great! so it is hausdorff
Comment: I didn't know that was a fact; I will verify that. Thank you :)
Comment: pleased that you have changed tag real analysis to general topology, but you should tag metric space.
Comment: One  thing  I do not understand  is  that  how  to  prove  the  sequence  $A_n$  is  decreasing  and  $A_{n+1}\subset A_n$ $?$
Answer:
Here is an example showing that the assumption that $H$ is Hausdorff is needed.

Let $H$ be the set of natural numbers $1,2,3,\ldots$ in the cofinite topology (the topology in which a subset is closed iff it is finite or the whole space).
And consider $f(n)=n+1$.
Here are some facts:
a) The space is $T_1$ (in fact, the minimal $T_1$-space on this set) but not Hausdorff.
b) Every subset, including the whole space, is compact (since the space is not Hausdorff, a compact subset does not have to be closed).
c) $f$ is continuous (the preimage of every closed set, which is either the whole space or a finite subset, is either the whole space or a finite, hence closed, subset).
d) Obviously, there is no subset $A$ such that $f(A)=A$ (the only sets $A$ such that $f(A)\subseteq A$ are inductive sets $H_n=\{n,n+1,n+2,\ldots\}$, but $f(H_n)=H_{n+1}\subsetneq H_n$).

However, as was mentioned by Une Femme Douce, if $H$ is compact Hausdorff, then for every continuous $f$ there is some $A$ such that $f(A)=A$. This is much easier to prove for a metric space, which seems to be the case after your comments.

Consider $A_0=H$, $A_n=f(A_{n-1})$. This is a monotonically decreasing sequence of compact (as images of compact sets under a continuous function), and hence, closed subsets. Their intersection $A=\cap_n A_n$ is non-empty.
Now, $f(A)=f(\cap_n A_n)\subseteq\cap_n f(A_n)=A$. Vice versa, suppose $z\in A$. Then for every $n$, there is $x_n\in A_n$ such that $f(x_n)=z\in A_{n+1}$. Since the space is compact and metric, it is sequentially compact, and there is a subsequence converging to some point $x$, and $x\in A$ (otherewise it is in some open set $H-A_j$ and no subsequence converges to it). Moreover, since $f$ is continuous and the space is Hausdorff, $f^{-1}(z)$ is closed and every $x_n\in f^{-1}(z)$, hence, $x\in f^{-1}(z)$, i.e. $f(x)=z$ and $z\in f(A)$. Overall, $A\subseteq f(A)$ and $A=f(A)$.

In the general case, we don't even need the assumption that $f$ is continuous, all we need that $f$ maps compact subsets to compact subsets. But the proof is different.
Comment: Is it obvious to see that the space you constructed is compact?
Unless I'm doing something wrong, it seems that the covering given by $1\cup \{2n\}_n, \{3n\}, \{5n\}, \{7n\}, \{11n\}$, etc. has no finite covering.
Comment: @TommyTang The sets you consider are not open in the finite complement topology. In the finite complement topology, for every set $A$, if an open set $U$ intersects it, then there are no more than a finite number of points left uncovered, so for each such point you can choose one open set from the covering, and you get a finite number of sets covering $A$.
Comment: Oh oops. Thanks!
Answer: In general, the answer is no. For example, let $H$ be a two-point space and $\omega$ be the function that swaps the two points.
Comment: Strictly speaking, such function fixes the whole $H$.


"Figured" woods and veneers for guitars

Question: I'm looking for an all solid wood guitar to purchase.  I recently came across a Takamine EG333C-LTD that is in my price range, but through my research I'm unable to determine if it is all solid wood construction.  Takamine's website indicates the guitar's top, back, and sides are all made of "figured" ash (whatever that means).  I did find one YouTube video that indicated the entire guitar was covered with an ash veneer, but I don't know if a veneer automatically eliminates an acoustic guitar from being considered 100% solid wood construction.  So my questions are:

What is "figured" wood?
If an acoustic guitar has a veneer is it considered "laminate" construction?
If an acoustic guitar has a veneer is it not considered "solid" construction?

Update:
I found a better description of the EG333C-LTD and unfortunately it appears to be laminate construction.
http://www.elderly.com/new_instruments/items/EG333CLTD.htm
Answer: Figured wood is wood with grain that is not straight, that has been cut along the grain to reveal pretty patterns. Think of walnut furniture (or just look at the photograph of the Takemine guitar).
Figured wood is often used as a veneer (for woodwork in general, not just musical instruments) because it makes less wood go further; using cheaper less visually attractive wood for interior structure. However figured wood is not necessarily veneer - solid walnut furniture is made; solid soundboards are made with figured wood.
A veneer would interfere with the vibration of a soundboard, and hence it would be dishonest to describe a veneered soundboard as being solid wood.
Whether a layer of solid wood with a veneer could be described as "laminate" is not really well defined. Strictly speaking it would be a laminate of two layers. But a typical laminate material for guitars has more than two layers.
All of this is important knowledge if you're building a guitar. When you're buying a guitar it's interesting, but academic.
You don't buy a guitar for the satisfaction of knowing what wood it's made of. You buy a guitar to play music with. So make your buying decision based on what it sounds like and how it feels to play (OK, most of us also care what it looks like). You could find a laminate guitar that plays beautifully. You could find a guitar made from the finest hardwood, that you just don't like the feel or sound of.
Regardless of whether the Takamine is veneered, they are a reputable company who make good quality guitars for the price -- but you'll only find out for sure by trying it out.
Unless you're willing to risk paying for a dud, never buy a guitar on specs alone. Try it in a shop before buying.
Answer: For a steel-string or nylon-string flat-top acoustic guitar, or for an archtop guitar, laminated back and sides are not necessarily a bad thing. Many luthiers and many players prefer laminated back and sides, noting that they create a more rigid, durable, stronger construction. In contrast, solid-wood back and sides are more delicate; they may crack over time due to fluctuations in temperature and humidity, or due to damage from banging around.
Everyone agrees that a solid wood top is superior to a laminated top in terms of its acoustical properties, for a flat-top steel-string or nylon-string guitar.
For an acoustic archtop guitar, a solid carved top is regarded as acoustically superior, but many manufacturers make archtop electric guitars where the top, back and sides are all made from pressed laminates, because they are more resistant to feedback from amplifiers on stage, they are more durable for touring purposes, and the woods are far less likely to crack from changes in temperature and humidity.
Answer: I am familiar with quilted, tiger striped (aka fiddle-back), and birdseye. These may be found in maple; I don't know what figure varieties exist in ash.
Yes, any veneer is a laminate.
Solid is a marvelous marketing word. Solid wood can be a laminate, like plywood. I would not expect a glued laminate to be the optimal choice for an acoustic soundboard. For an electric guitar, veneered solid-body models are common. (The quilted example is just that; a 1/4" maple top  over a 2-pc mahogany body. Most veneers, however, are very very thin.)
Comment: You are quite mistaken in your usage. "Solid wood" means one thickness of solid wood. No manufacturer would ever use the word "solid" when they mean "laminate" or "plywood." Those are separate terms. Furthermore, in guitar construction, the term "laminate" with regard to a top or back or sides of an acoustic guitar means at least three layers of wood. A laminate top on a solid-body electric guitar is another matter.
Comment: Solid, liquid, or gas? Yes, the term solid can be abused by those intending to mislead.

"Figured" woods and veneers for guitars


Can these two limits be true at the same time

Question: Is it possible to have $$\lim_{x\to+\infty}x\left[f(x)\right]^5=0$$ and $$\lim_{x\to+\infty}x\left[f(x)\right]^3=+\infty$$ for some function $f$ at the same time?
Comment: Does $f^3(x)$ mean $[f(x)]^3$ or $f(f(f(x)))$?
Comment: Take $f(x)=x^{-\frac{1}{4}}$
Answer: Hint: Consider $x\mapsto x^\alpha$, for an appropriate $\alpha$.
Answer: Yes. For example, $f(x)=\dfrac{1}{\sqrt[4]x}$
$\lim\limits_{x\to\infty} \dfrac{x}{(\sqrt[4]{x})^3}=\infty$
$\lim\limits_{x\to\infty} \dfrac{x}{(\sqrt[4]x)^5}=0$
Answer: If you look at $$L(n)=\lim_{x\to+\infty}xf^n(x)$$ as Git Gud suggested, use $f(x)=x^a$ and so you search for $$L(n)=\lim_{x\to+\infty}x^{an+1}$$ So, if $an+1 \gt 0$, the limit is $\infty$ and if $an+1 \lt 0$, the limit is $0$.
Answer: Assume $f(x) = x^P$, then to satisfy conditions listed,

$x^{5P + 1} \rightarrow 0 \Rightarrow 5P + 1 < 0$
$x^{3P + 1} \rightarrow \infty \Rightarrow 3P + 1 > 0$

So you get: $f(x) = x^P$, where $P \in \left]-\dfrac{1}{3}, -\dfrac{1}{5}\right[$


How to find all rows where sum of a column in an associated model is greater than x

Question: I am new to sequelize.js.
I am working on a minor project using mysql with sequelize.js to store data.
I have Member and Loan models.
 var Member = sequelize.define('members', {
    rollNumber: {
        type: Sequelize.INTEGER,
        unique:true,
        primaryKey:true,
        unsigned:true
    },
    firstName: {
        type: Sequelize.STRING(20)
    },
    middleName: {
        type: Sequelize.STRING(20)
    },
    lastName: {
        type: Sequelize.STRING(20)
    },

    idNumber: {
        type: Sequelize.STRING(20),
        unique:true,
    },
    mobileNumber: {
        type: Sequelize.STRING(20)
    }
});

 var Loan = sequelize.define('loans',{
    memberRollNumber:{
        type: Sequelize.INTEGER,
        references: { model: Member, key: "rollNumber" },
        allowNull: false
    },
    disbursedAmount:{
      type: Sequelize.FLOAT
    },
    interestRate:{
        type: Sequelize.FLOAT
    },

    initialBalance:{
        type: Sequelize.FLOAT
    },
    duration:{
        type: Sequelize.INTEGER
    },
    disbursementDate:{
        type: Sequelize.DATEONLY
    },
    dueDate:{
        type: Sequelize.DATEONLY
    }
});

Loan.belongsTo(Member);
Member.hasMany(Loan);
Now here, I want to get all the members whose sum of Loan.initialBalance is greater than "1000" or any other number.
function getLoans(callback){
    Member.findAll({
        include: [ Loan ] ,
        where:{}
    }).then(function (members) {

        callback(members)
    })
}

I have spent hours trying to figure out what goes in the where:{} clause. Please advice on possible solutions.
Comment: You cannot filter on aggregated values in the where clause (unless aggregation happens in a subquery), you need the having clause.
Comment: @Shadow please show an example
Comment: I do not know sequelize.js, so I can't.
Answer: For that you need to do it via group_by and having , and here is how you can do that with sequelize :
Member.findAll({
    include : {
        model : Loan
        attributes : [],
        required : true
    },
    group : ['members.id','loans.initial_balance'],
    having : {
        $and : [
            // condition to check sum of initialBalance is greater than 1000
            sequelize.where(sequelize.fn('sum', sequelize.col('initial_balance')), { $gt : 1000 }) ,
        ]
    }
})

Note : Please change column name as per your DB.


Any great *Introductory* books for Finite (Element/Difference) Methods

Question: I sort of have two questions on the same subject so I just thought to ask both in one thread.
I am looking to do some research on Finite Element Methods (FEM) and I am recently started looking into the related different methods such as Finite Difference Methods (FDM) and Finite Volume Methods (FVM). Assuming I will do the research on (FEM), I wanted to ask what were some good books that will be suitable for a beginner in this subject field topic with more so a electrical engineering and math background? I am not sure if there are any applications for these methods to use in the field of electrical engineering or similar topics, but this is what type of books I am most concerned to look for. I am also interested in the traditional subject field topics these methods are used for such as (viscosity, collisions, structure analysis,$\;\ldots$ etc.), from more of a Applied Math stand point/background.
My second question is, I am still unsure which method would be most suitable for a beginning learner on this topic and most beneficial for the electrical applications (preferably). I hear that the (FEM) is the most difficult method of the three for one who is just starting to pursue interest in this field of study. I hear that the (FDM) and (FVM) are the two that are more accessible and easy to pick up on for the first time then (FEM). Any our your suggestions would be greatly appreciated whether they are from just reading or from actual personal experience or someone you may know experience when it came to dealing with this in real life practice. So again, to summarize, my question is what method do you feel would be best to start off with learning with the preferred topics of interest  stating above which are electrical phenomena or the latter (viscosity,$~\ldots$). In the long run I would like to have experience with each method (as a side note).
Thank You.
Answer: I would start by learning the FEM for elliptic problems as this is the easiest. The book Numerical Solution of Partial Differential Equations by the Finite Element Method by Claes Johnson is a fairly good introductory book if you are mainly interested in implementing and using the finite element method. It skips most of the Hilbert space theory needed to make the arguments rigorous. It also skips most of the technical difficulties. On the other hand, if you want a rigorous treatment I recommend just reading a book on the Hilbert space approach to PDE as a complementary text. I thought Introduction to PDE by Renardy and Rogers (especially chapters 6-8) to be a gentle introduction to this topic. There is also a great deal of work done on constructing approximation spaces and finding error approximations in p-norms rather than the Sobolev estimates the FEM gives you via Cea's Lemma. I found this to be the hardest part and would leave it for last. As for you second question, no, I don't think learning the FEM before the FDM will cause major problems.
Comment: Thanks alot for that info.


css logo link not working on IE or firefox

Question: I tried everything I know and I can't find out why on IE and Firefox the link underneath the logo ("next meeting or event") does not work at all. Here is my css:
/*logo*/
.nav-logo {
float:left;
width: 260px;
margin-left: .2em;
z-index: 1;}

.nav-logo top {
float:left;
width: 250px;
cursor: pointer;}

.event {
float:left;
margin-left: 0;
margin-top:-8px;
cursor: pointer;
clear: both;}

/* Nav width setting*/
.nav-hold {
width: 98%;
max-width: 1000px;
margin: 0 auto;}

/* NAVIGATION */
.nav-bar {
width: 100%;
height: 80px;
background-image:url(../images/bg-menu80.jpg);}

.nav-hold {
overflow:hidden;}

.nav-list {
float: right;
list-style: none;}

.nav-list li {
float: left;
width: auto;
position: relative;}

.nav-list li a {
text-decoration: none;
display:block;
padding: 30px 7px 28px 7px;
color: #f9f9f9;
font-size: .9em;
font-weight: bold;}

.nav-list li ul {
display: none;
list-style: none;
position: absolute;
margin: 0;
padding: 0;
width: 70px;}

.nav-list li ul li {
margin: 0;
padding: 0;}

.nav-list li:hover ul {
display: block;}

.nav-list li a:hover li {
float: left;}

.nav-list li:hover li a {
background-color: #333;
border-bottom: 1px solid #fff;
color: #FFF;
height:50px;
width:150px;}

.nav-list li a:hover {
text-decoration: none;
display: block;
padding: 30px 7px 28px 7px;
color: #000;
font-size: .9em;
font-weight: bold;
background-color: #e7e4e4;}

I hope I'm writing the code here correctly, please you can see the page here:
http://www.vosgrafica.com/LIEG/index.html
Thanks to all, I really appreciate it!
Answer:
 is in front of the link. Change its z-index to a lower value.
Comment: Hi Christine and thank you! I tried your suggestion and the navigation appear without the background image and the logo in the wrong position... any other idea?   thank you again!
Comment: Hello Rigo. Sorry, I don't know what you mean by "wrong position". It looks right for me and your link works now, too.