Display data into an EXTJS Grid Panel

Question: I am trying to make a gridview and I am able to do that successfully using hardcoded data.
var store = Ext.create('Ext.data.Store', {
        storeId: 'myData',
        //url: 'GridViewController',
        fields: [
            { name: 'Q1', type: 'int' },
            { name: 'Q2', type: 'int' },
            { name: 'Q3', type: 'int' },
            { name: 'Q4', type: 'int' },
            { name: 'Q5', type: 'int' },
            { name: 'Improvements', type: 'string' },
            { name: 'Comments', type: 'string'}],
        data: { 'items': [
        { "Q1": "1", "Q2": "2", "Q3": "4", "Q4": "4", "Q5": "5", "Improvements": "Wut Is Up", "Comments": "Nothing" },
        { "Q1": "1", "Q2": "1", "Q3": "3", "Q4": "4", "Q5": "5", "Improvements": "Wut Is Up1", "Comments": "Nothing13"}]
        },
        proxy: {
            type: 'memory',
            //url: 'GridViewController'
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    //store.load();
    this.grid = Ext.create('Ext.grid.Panel', {
        title: 'GridView App',
        store: Ext.data.StoreManager.lookup('myData'),
        columns: [
        //{ id: 'id', header: 'ID', width: 30,
        //    sortable: true, dataIndex: 'id'
        //},
        {header: 'Q1', width: 100, sortable: true, dataIndex: 'Q1' },
        { header: 'Q2', width: 100, sortable: true, dataIndex: 'Q2' },
        { header: 'Q3', width: 100, sortable: true, dataIndex: 'Q3' },
        { header: 'Q4', width: 100, sortable: true, dataIndex: 'Q4' },
        { header: 'Improvements', width: 200, sortable: true, dataIndex: 'Improvements' },
        { header: 'Comments', width: 200, sortable: true, dataIndex: 'Comments' }
    ],
        stripeRows: true,
        //height:250,
        width: 800,
        renderTo: Ext.getBody()
    });

This works fine... But now I want to get data from sql db and use URL... like url:GridViewController (like in the code)...
here's my contoller
public void GridViewController()
    {

        Response.Write("Survey Completed!");
        SqlConnection conn = DBTools.GetDBConnection("ApplicationServices2");
        string sqlquery = "Select Q1, Q2, Q3, Q4, Improvements, Comments FROM MyTable";
        SqlCommand cmd = new SqlCommand(sqlquery, conn);

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
                //json.Add(reader.GetInt32(0), reader.GetString(1));
            reader.Close();
        }

        //cmd.Connection = conn;
        conn.Open();
        //cmd.ExecuteNonQuery();
        conn.Close();

    }

I am lost as to how to implement this. Please help. Any Input will be highly appreciated.
Comment: It will help if you confirm your proxy type with a url (it won't work with `memory`), and it will also be helpful to see the server response.
Comment: You can use FireBug of Chrome developer tools for that. On Chrome open the developer tools; select `Network` for the top tool bar and then `XHR` from the bottom one. It will show you all server requests and their response. The console will also show you any Javascript errors.
Comment: Thank you Izhaki... that's the whole point... i am not sure what will work... I put proxy as memory for the hardcoded data... To get data from json throu sqldata it will be type: 'ajax'... and i haven't even gotten to the server response part yet... how do i do that... Thank you for taking time to read my post Izhaki
Comment: I am sorry if I sound dumb, but don't I have to implement a query to get the data from sql db... that is what I am doing in my GridViewController()... this is where I give sql select statement but I am not sure on how to save those data in an array and then encode it as JSON and send the data back..
Comment: Oh, so it's a server side question? What Server side technology you're using (sorry, can't recognise it).
Comment: I am sorry, i should have mentioned that... I am using asp.net... trying to do this whole thing on visual studio on C#
Comment: I'd recommend you add these tags to the your question - these guys will surely be able to help you more than ExtJS experts. The json format you should be returning can be seen (nearly) at the bottom of [this docs page](http://docs.sencha.com/ext-js/4-1/#!/guide/editable_grid)
Comment: Ya I can see that in the doc page, but don't know how to implement that with sql data in c#... If I could get some pointer on how I can store the data into an array and encode it as JSON, that would help me a lot...
Answer: window.App.myData = Ext.create("Ext.data.Store", {
    "model": Ext.define(Ext.id(), {
        extend: "Ext.data.Model",
        "fields": [{ name: 'Q1', type: 'int' },
        { name: 'Q2', type: 'int' },
        { name: 'Q3', type: 'int' },
        { name: 'Q4', type: 'int' },
        { name: 'Q5', type: 'int' },
        { name: 'Improvements', type: 'string' },
        { name: 'Comments', type: 'string'}
        ]
    }),
    "storeId": "myData ",
    "useIdConfirmation": true,
    "autoLoad": true,
    "proxy": {
        "type": "ajax",
        "reader": {
            "type": "json",
            "idProperty": "Q1",
            "root": "data",
            "totalProperty": "total"
        },
        "url": "/<here you have to give controller>/<here you have to give method where u get the data>"
    }
});

//Now Create ur grid like this
Ext.create("Ext.grid.Panel", {
    "id": "grid1",
    "border": false,
    "cls": "x-grid-custom",
    "renderTo": Ext.getBody(),
    "width": 218,
    "bodyStyle": "padding:0 0 0 0;",
    "header": false,
    "columns": {
        "id": "ColumnModel5",
        "items": [{
            "id": "Q1",
            "header": "Q1 data",
            "width": 130,
            "dataIndex": "Q1",
            "hideable": false,
            "sortable": true,
            "wrap": true
        }, {
            "id": "Q2",
            "header": "Q2 data",
            "width": 130,
            "dataIndex": "Q2",
            "hideable": false,
            "sortable": true,
            "wrap": true
        },{
            "id": "Q3",
            "header": "Q3 data",
            "width": 130,
            "dataIndex": "Q3",
            "hideable": false,
            "sortable": true,
            "wrap": true
        },{
            "id": "Q4",
            "header": "Q4 data",
            "width": 130,
            "dataIndex": "Q4",
            "hideable": false,
            "sortable": true,
            "wrap": true
        }
         .
         .
         . //do the same thing for other columns
        ]
    },
    "enableColumnMove": false,
    "enableColumnResize": false,
    "store": "myData"
});

Comment: Thanks @Radim... This was an old question that I completely forgot about :)

Display data into an EXTJS Grid Panel


How to load elements of clearcase view to local file system

Question: I'm looking out for cleartool command which retrieves all the elments(files) of the given path (myvob\projects\projectname) and stores them in the local file system.
This makes me avoid creating the view again with the same config spec just to see the contents of the view and not to perform any modifications.
Answer: Actually, creating a snapshot view with a specif load rule just for that path would be the more efficient way to do it.
If you don't want to create a view each time you need such a file consultation, I would still recommend to create a dynamic view (but only once), with a config spec you can change at will.
Since it is a dynamic view, you will be able to tweak that config spec and see the files instantly. Once you have the right versions, you can copy them wherever you want on your disk.


Where em um array

Question: Tenho a seguinte Query:
SELECT u.user_nome
FROM tb_Usuario u
WHERE u.user_ativo = 1

Preciso mais uma cláusula where onde a mesma comparar um id do usuário. Porém, recebo esse id através de um array, como faço para fazer essa comparação?
Array:
(
  [0] => 1-funil-pr-
  [1] => 3-funil-pr-2
)

Recebo estes dois parâmetros id.
Comment: vê isto http://stackoverflow.com/questions/907806/php-mysql-using-an-array-in-where-clause @Fred
Comment: esse array é recebido pelo fetch_array ou esse array vem de outro lugar, está um pouco confuso
Answer: Pode usar a função IN, para mais informações veja no SO ou MySQL, deixo um exemplo:
$array = array(1, 4, 5, 7);

$sql = 'SELECT *
        FROM `table`
        WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

Answer: A respostas do @Tmc funciona, porem utilizam concatenação de SQL, algo que considero não ser a melhor forma.
Recomendo utilizar prepared Statements conforme descrito nesta pergunta.
A sua consulta pode ser feita da seguinte forma:
$arrTokens = ["1", "18", "35"];
$qtdElementos = count($arrTokens);
$arrInterrogacoes = array_fill("0", $qtdElementos, "?");

$sql = "SELECT u.user_nome FROM tb_Usuario u WHERE u.user_ativo = 1 AND u.user_slug IN (";
$sql .= implode(",", $arrInterrogacoes);
$sql .= ")";

$statement = $suaConexaoPDO->prepare($sql);

for($i = 0; $i < $qtdElementos; $i++) {
  $statement->bindValue($i, $arrTokens[$i]);
}

$statement->execute();

Answer: Resolvido!
$recebe_do_controller = $data->recebe_do_controller; //DADOS RECEBIDOS DO CONTROLLER
$array_explode = explode(',', $recebe_do_controller); //FIZ O EXPLODE NO ARRAY PRQ PRECISEI UTILIZÁ-LO EM OUTRAS FUNÇÕES.
$array_implode = "('".implode("','", $array_explode)."')"; //IMPLODE ARRAY PARA PODER UTILIZAR AS INFORMAÇÕES NA QUERY

SELECT
 u.user_nome
FROM
 tb_Usuario u
WHERE
 u.user_ativo = 1 AND u.user_slug IN ".$array_implode.";

Comment: Esta solução permite injeção de código SQL. Veja esta pergunta: http://pt.stackoverflow.com/questions/3864/como-prevenir-inje%c3%a7%c3%a3o-de-c%c3%b3digo-sql-no-meu-c%c3%b3digo-php

Where em um array


Pros/cons of NRPE and SNMP with Nagios 3?

Question: I have been using Nagios 3 with NRPE on the clients for some time now, and it works great.
Now I heard that if I used SNMP I wouldn't have to install check_ plugins on each client.
So does anyone knows of pros and cons of NRPE vs. SNMP?
My monitor server is a CentOS5 with Nagios 3 and the client are mostly CentOS and Ubuntu.
Answer: SNMP is available for everything, Linux, Unix, Windows, Cisco.. and many more.
Certain information will be available on NRPE that isn't on SNMP. Your setup time with snmpd will be allot quicker, once you get your head around how SNMP works.
You can provide a snmpd.conf config to your clients and they can setup their own snmp daemon quickly and without too much trouble shooting on your behalf. I imagine you requesting access to clients servers to install NRPE. Depending on your install method, your clients systems may not be keeping NRPE up-to-date, unlike snmp which is very mature and guaranteed to be maintained by the distributions package management system!
save yourself some effort and avoid using NRPE unless snmp can not provide Nagios with the correct information.
Comment: just some corrections: nrpe is available and maintained by distributions or serious/reliable repositores (like the dag repo for centos/red hat). Installing snmpd is as much a pain as installing nrpe, that is, just a few keystrokes away. Distributing a config file for nrpe if you have a configuration management system (which you should) like CFengine is no more difficult than for snmpd. So frankly, I fail to see why recommend avoid using NRPE for those reasons. I can understand you prefer SNMP to NRPE, but not for those reasons :)
Comment: +1 I agree with you snmp still limited and I don't see why using it even to deploy the native agent monitoring ( nrpe ). Only one case occur is when you can not open tcp port on the client machine for nrpe.
Answer: There is nothing saying you can't we both!
SNMP is Nice but just like NRPE may not be installed. also SNMP support in windows... Sucks. A big advantage of NRPE is that a lot of the scripts out there are written for NRPE and may Need some hacking to get working with SNMP.
Comment: +1; we use both extensively. Some checks are easier with SNMP, some with NRPE.
Comment: Interesting. Can you give some examples where you thought SNMP were the right thing to use instead of NRPE?
Comment: well, some nagios plugins are already written for SNMP, so I am not going to reinvent the wheel just to run them through NRPE. Think of stuff like the check_hpasm for HP server hardware, for instance. It's more convenient/easier/faster to use an existing script than to write your own.
Answer: SNMP is tried, true, and as Ash Palmer indicated, supported by almost everything.  Its configuration is pretty simple, and provides you with a wealth of statistics for most platforms.
Also, the SNMP protocol has support for traps, which are a notification system that doesn't rely on polling (something that I don't think the check_ plugins do).
SNMP is also pretty low-cost in terms of network and CPU.
If you need additional data available via SNMP, that's doable too, but probably a bigger challenge than an NRPE.
Finally, the SNMP protocol version three has secure authentication and encryption built into the protocol.


If $X \sim \mathcal{P}(u)$, show that $S=(-1)^X$ is the UMVUE of $e^{2u}$

Question:
If $X \sim \mathcal{P}(u)$, show that $S=(-1)^X$ is the UMVUE of
  $e^{2u}$.

I can't figure this out, finding UMVUE always confuses me. Any help is greatly appreciated
Comment: What does "$\mathcal{P}(u)$" mean?
Comment: @whuber I believe he refers to the Poisson distribution with mean $u$, at least I took it as such.
Answer: -What is the sufficient statistic for one observation coming from a Poisson distribution?
-Is your estimator unbiased?
-Is it a function of the sufficient statistic?
-Is the family of that sufficient statistic complete?
If you find the sufficient statistic and also find that the answer to the following three questions is affirmative, then you are done.


Use semantics to prove that the postcondition is true following the execution of the program assuming the precondition is true

Question: I am trying to study for a test in my programming language concepts class.
I am trying to understand how to solve this problem. Our professor said we don't need to use formal notation to prove the problem as long as he can understand what we are saying.
I missed the lecture where he solved the problem and I'm having a very hard time finding resources to help me solve it on my own.
Would be so thankful for an explanation.
Problem

Use axiomatic semantics to prove that the postcondition is true following the execution of the program assuming the precondition is true

Precondition: n ≥ 0 and A contains n elements indexed from 0

bound = n;
while (bound > 0) {
  t = 0;
  for (i = 0; i < bound-1; i++) {
    if (A[i] > A[i+1]) {
      swap = A[i];
      A[i] = A[i+1];
      A[i+1] = swap;
      t = i+1;
    }
  }
  bound = t;
}

Postcondition: A[0] ≤ A[1] ≤ ...≤ A[n-1]

Answer: Lets number the lines for reference:
 1. bound = n;
 2. while (bound > 0) {
 3.  t = 0;
 4.  for (i = 0; i < bound-1; i++) {
 5.    if (A[i] > A[i+1]) {
 6.      swap = A[i];
 7.      A[i] = A[i+1];
 8.      A[i+1] = swap;
 9.      t = i+1;
10.    }
11.  }
12.  bound = t;
13. }

Consider the following assertions:

Before entering 12
t < bound

Before entering 11
A[i] <= A[t] for all i such that 0 <= i < t
Before entering 13
A[k] <= A[j] for all indexes k and j such that bound <= k <= j <= n-1
After leaving 12
bound has decreased

Let's see now why the assertions are true

This is true because t=0 before the loop and if set inside the if it is
t = i + 1 < (bound - 1) + 1 = bound.

This is true because otherwise a swap would have happened.
This is true because of 2 and because the for doesn't change entries with indexes j from bound to n-1.
This is true because of 1.

From assertion 4 we deduce that the while loop, and so the algorithm, finishes in n steps at most, when bound = 0.
The postcondition now follows from assertion 3 for bound = 0.


Dataset with two unique trends?

Question: I have a scatterplot displaying one data set that, at first glance, has a weak negative correlation. Upon further inspection, however, it appears that the data set shows two stronger linear trends that seem to separate after a certain threshold. Is it possible for a single dataset to display multiple trends? I assume it would be intrinsic to whatever information you are studying/graphing but I'm not sure if the results are reasonable. Thanks!

Comment: Welcome to Cross Validated! To what do the dot colors in the right graph correspond? Is there a blue group and a red group, for instance?
Answer: I also see two trend lines in your data, but they go in the opposite direction of yours!

The human brain has an awesome power to find patterns in random data. Without a prior hypothesis (or a covariate that defines two groups of data points), I'd be very wary of defining two lines in a bunch of very scattered points.
Answer: It's certainly possible -- you show an example of it happening. Another example would be the relation between height and weight, separately for men and women. If you lumped them all together, there would be a positive trend, but it would be much stronger with sex added as a variable.
This is one of the big advantages of adding covariates to your model.
One key question will be if you can figure out what separates the points on the two lines. If you're just finding things after looking at the data, then that's fishing and has to be done very carefully.  It's also called HARKing (hypothesizing after results are known).
You would need to separate the purely exploratory work from hypothesis testing.

Dataset with two unique trends?


and  links not generated as https:

Question: I am new to Drupal and having an issue relating to SSL. The view I'm working with is using the jcarousel module to display images with links.
The data contains a link and image source. All of the links are entered using relative paths to the root of the site.
The home page has 5 links on it. When the you look at the source from the generated page, 2 of the links are https and the other 3 http even though none have the base URL in the link data.
I have added $_SERVER['HTTPS'] = 'on'; to settings.php but that hasn't corrected the issue.
What is the proper way to force both tags to be generated with https: links?
Comment: Thank you Pierre! I usually have good luck with Google and it is rare I post a question. I have much to learn.
Comment: Voilà, now we have a real (+ good I think) question, +1. Only 1 more suggestion (if you don't mind): I ***guess*** the (rather critical) word ***all*** is still missing in your last phrase. Apart from that: I'd make that question also the title of your question (it's the summary of it all, no?). good luck!
Answer: Take a look at this answer, I believe it goes into great detail about enabling SSL support on pages and image assets for Drupal 7;
How to force drupal 7 to load HTTPS assets?
Also if your still having problems, take a look at this documentation on drupal.org;
https://www.drupal.org/https-information
Hope that helps!

and  links not generated as https:


Making a counter increment with passing of system time

Question: Below is my attempt of having the counter variable increment as each second passes by. It's not working like I thought it would. I think the problem is in the while loop of trying to compare old time to new time to measure if a second has passed.
import time as time
import tkinter as tk

root = tk.Tk()
root.geometry('200x200')

months = {'1': 'Month of Flowers',
          '2': 'Month of Moon',
          '3': 'Month of Dragon'}

hours = {'1': '1st hour',
         '2': '2nd hour',
         '3': '3rd hour'}

system_time = tk.Label(root, text=f'{time.time()}')
system_counter = tk.Label(root, text='0')
game_time_month = tk.Label(root, text='Month')
game_time_hour = tk.Label(root, text='Hour')

system_time.pack()
system_counter.pack()
game_time_month.pack()
game_time_hour.pack()

def update_all_time():
    system_time['text'] = f'{time.time()}'
    game_time_month['text'] = 'Month'
    game_time_hour['text'] = 'Hour'
    root.update()

system_timer_old = time.time()
counter = 0
while True:
    system_timer_new = time.time()
    if system_timer_new == system_timer_old + 1:
        counter = counter + 1
        system_counter['text'] = 1
    update_all_time()

root.mainloop()

Comment: What error are you getting?
Comment: There is no error. It's just nothing happening.
Comment: Problem could be because you are calling `time.time()` multiple times , also `system_timer_new == system_timer_old + 1` may not yield True at all, as the return value is a high precision float. And its a millisecond timestamp. I suppose you are looking for seconds here ?
Comment: Yes. I want to increment the counter every second that passes.
Answer: It only increases if system_timer_new is exactly 1 more than the old system_timer. Consider using a window or a limit? I.e. it will never trigger if your time difference is not exactly 1. Consider using a window or a limit to trigger the increase of your counter. You could also use datetime function of timedelta as well.
if system_time_new >= system_time_old:
    delta = system_time_new - system_time_old

Answer: A counter of how many seconds have passed is, essentially, a clock. Don't try to implement your own clock; just use one from the standard library.
The correct value of the counter is simply the number of seconds that have elapsed since the counting started, rounded down to an integer. So, the function below returns the current value of what the counter should be; you can call it from anywhere that you want to get the value of the counter.
import time

start_time = time.monotonic()

def get_counter():
    current_time = time.monotonic()
    return int(current_time - start_time)

Answer: Tkinter has a method specifically for scheduling functions to be called in the future. If you want to update a counter every second, it looks something like this:
def update_counter():
    global counter
    counter += 1
    system_counter['text'] = counter
    system_counter.after(1000, update_counter)

With that, the function will update the counter, update the label with the new value, and then schedule itself to run again in 1 second (1000 milliseconds). You only need to run this function once, and it will continue to execute once a second.


Eventos onmouseover e onmouseout demorando a trocar imagens

Question: Estou com um problema ao utilizar os eventos onmouseover e onmouseout que ao passar o mouse ele faz a troca das imagens mas ele é muito lento demora muito, existe outra forma para fazer isso seguindo o exemplo abaixo.

Comment: Bruno, tens mais imagens que precisem dessa funcionalidade ou é só uma caso único?
Comment: Você quer trocar as imagens ou só colocá-la em escala de cinza? Se for só escala de cinza, não precisa ser outra imagem
Answer: Já tentou com css? Vou dar um exemplo.

span.switch {
  border: 1px solid black;
  cursor: pointer;
  display: block;
  width: 40px;
  height: 40px;
  background: url('http://thumb10.shutterstock.com/photos/thumb_large/546601/113982157.jpg') no-repeat 0px 0px
}
span.switch:hover {
  background-position: 0px -37px;
}

Dessa maneira, existe apenas uma única imagem que é carregada uma única vez. Quando passamos o mouse por cima da imagem, o CSS apenas muda a posição do background.
Answer: Talvez seja o caso de fazer um preload da imagem secundária antes de mostrar a primária. As imagens abaixo tem 900 e 700 KB, imagens maiores podem ser encontradas aqui.

function preloadImagem( url )
{
    var img = new Image();
    img.src = url;
    img.onload = function () {
        var container = document.getElementById('img2');
        container.style.display = 'block';
    };
}
preloadImagem( 'http://upload.wikimedia.org/wikipedia/commons/5/59/Blomster.jpg?v=3' );

Referência: JavaScript Preloading Images
Answer: Usa o img:hover, define um background-image pro img, e depois outra background-image para o img:hover, eu pelo menos faria assim.
Se ajudar, http://www.corelangs.com/css/box/hover.html


There are no rational $a, b, c $ with $a+b\sqrt{u}+c\sqrt{v} =\sqrt{uv} $

Question: If $u$ and  $v$
are rationals such that
 $\sqrt{u}, \sqrt{v}, $ and $\sqrt{uv}$
are all irrational,
show that there are no
rational $a, b, $ and $c$
such that
$a+b\sqrt{u}+c\sqrt{v}
=\sqrt{uv}
$.
This is a generalization
of my answer
to this question:
Proof by contradiction: finding integers that satisfy $a+b\sqrt{2}+c\sqrt{3}=\sqrt{6}$.
I will post a solution
in two days
if there are
no posted solutions.
Comment: I don't see what are you looking for: a simpler proof? That's because you can take exactly the one you posted with $u,v$ replacing $2,3$.
Comment: That is what I did. But I thought that this generalization was interesting.
Answer: Note that $$a+b\sqrt{u}+c\sqrt{v} +\sqrt{uv}=(\sqrt u+c)(\sqrt v+b)+(a-bc).$$
Now if there is a $t\in\Bbb{Q}\setminus\{0\}$ such that $\sqrt u+c=t$ and  $\sqrt v+b=\dfrac{bc-a}{t},$ then  $\sqrt u,\sqrt v\in\Bbb{Q}$ which contradicts to your assumption.
Hence $(\sqrt u+c)(\sqrt v+b)\notin\Bbb{Q}\,\,\,\,\,\forall b,c\in\Bbb{Q}.$
There is a very nice generalization of this argument.
Answer: Lemma:  $\sqrt{u}$ and $\sqrt{v}$ must be linearly independent over the rationals.
Else $a \sqrt{u} + b \sqrt{v} \in \mathbb{Q}$ with $a,b \in \mathbb{Q} \setminus \{0\}$ $\implies$ $(a \sqrt{u} + b \sqrt{v})^2 = a^2 u + b^2 v + 2ab \sqrt{uv} \in \mathbb{Q}$ $\implies$ $\sqrt{uv} \in \mathbb{Q}$, contrary to the hypothesis.
Proof:
$$
\sqrt{uv}=a+b\sqrt{u}+c\sqrt{v} \quad\quad \Big| \cdot \sqrt{u}
$$
$$
\begin{align}
u \sqrt{v} & =a\sqrt{u}+bu+c\sqrt{uv} \\
 & = a\sqrt{u}+bu+c(a+b\sqrt{u}+c\sqrt{v}) \\
 & = (a+bc)\sqrt{u} + c^2 \sqrt{v} + ac + bu
\end{align}
$$
By the linear independence proved in the lemma, the coefficients of $\sqrt{v}$ must match i.e. $\,u = c^2\,$ but that contradicts the irrationality of $\sqrt{u}$.
Answer: Here's a sketch of a proof (without looking at yours).
Suppose there's some such combination. Square both sides to get an expression involving $\sqrt{uv}$. Isolate that term to get an expression of $\sqrt{uv}$ as a rational combination of $\sqrt{u}$, $\sqrt{v}$ and $1$.
Set this equal to the supposed expression for $\sqrt{uv}$ that you started with, and move everything to one side. You end up with a rational combination of $1, \sqrt{u}, \sqrt{v}$ that's zero. Write this in the form
$$
A = B \sqrt{u} + C\sqrt{v}
$$
and square it to get
$$
A^2 = B^2 u + C^2 v + 2BC \sqrt{uv}
$$
from which we see that $\sqrt{uv}$ is written as a linear combination of rationals, which is a contradiction.
Yeah, you have to worry about various coefficients not being zero. That's why I said it was a sketch. :)
Comment: Fill in the details and I might accept.
Answer: Let $r = \sqrt{u}, s = \sqrt{v}\implies a + br + cs = rs\implies s = \dfrac{a+br}{r-c}\implies s^2 \in \mathbb{Q}\implies r \in \mathbb{Q}$ since $r^2 \in \mathbb{Q}$, contradiction to $r \in \mathbb{Q^c}$. Thus there are no $a,b,c$ which "satisfies" the given condition.
Comment: Where have you used the part of the hypothesis that says $\sqrt{uv}$ is irrational?
Comment: The proof I employed does not require the use of the information that you pointed out.
Comment: Good catch. Working out the algebra, I get that $s^2(r^2+c^2)-a^2-b^2r^2 = 2r(ab+cs^2)$ so that $ab+cs^2=0$ and $s^2(r^2+c^2)-a^2-b^2r^2=0$ which looks harder than my original proof.
Comment: @DeepSea Without that condition $2+\sqrt{2}-\sqrt{2}=\sqrt{4}$.


why does the jquery change event not trigger though the value of input changed indeedly?

Question: JSFIDDLE

Html Code:

    <input value="123">
    <button>button</button>

Js Code(using JQuery 1.2.0):
$(function(){
    $("button").click(function(){
        $("input").val("balabala...");
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

Question:
At the beginning, the value of the input is "123".

When I change the text through editing by hands and click other places not the input field, the change event of the input will trigger.

However, when I click the button, which will also change the value of the input, the change event of the input will not work.

Thanks for any help.
Comment: See also: http://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery
Comment: @Todd, thanks, they are similar and near to the same.
Answer: The change event is not triggered when changing the value programatically with code, you have to trigger it yourself
$(function(){
    $("button").click(function(){
        $("input").val("balabala...").trigger('change');
    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});

FIDDLE
Comment: Ooh, just out of interest, what's the difference between using `.trigger('change')` and `.change()`?
Comment: No difference for this case really, jQuery just has a special `trigger()` method that does this, and it accepts more options than just using `.change()`
Comment: @BeatAlex Both of methods work, but I do not know the difference in details.
Answer: JSFiddle
You need to append .change() onto the click function:
$(function(){
    $("button").click(function(){
        $("input").val("balabala...").change();

    });

    $("body").on("change","input",function(){
        alert("change");
        alert($("input").val());
    });
});


How to update UI for callback received while app is in background?

Question: I am creating an android application using MVP architecture. I have created Presenter and Interactor classes. I am struggling to update UI when app is in background and comes back to foreground.
Let's consider following scenario.
Button on UI is clicked and presenter is notified about it. Presenter asked Interactor to provide data from backend. By the time Interactor provides result to presenter somehow UI is in background. How can I save the state of it and change UI components once app is in foreground.
I tried doing following things:

Using flags (turn on the flag and check in onResume to call the method that supposed to be called when callback received. But problem is that let's say if I have 5 different services that can be called by presenter which has different callback then I will require 5 flags which I don't like it)
Using JAVA reflection (Store the name of method be called in HashMap with parameter)

Is there any better way to achieve this?
Comment: Subscribe to a BehaviorRelay or reactive database which gives you the response that is relevant to your currently displayed data at any time you subscribe to its initial state or future changes
Comment: @EpicPandaForce can you share any example?
Answer: As name MVP Suggests Model View Presenter
Model : Model is responsible for getter setter methods also known as POJO.
View : Contains activities/fragments with views.
Presenter : Actual Business Logic where you can communicate network calls OR relate with backend databases such as SQLite / MySql.
When button click you need to call presenter which will perform background tasks once it is done you need to notify your view that the response is Success/Failure via CallBacks which done with the help of interfaces.
Example:
<code>interface BaseContract {
        interface BaseView {
            //Methods for View
            void onDoSomething();
        }

        interface BasePresenter {
            void doSomething();

        }
    }

    class BaseMainPresenter implements BaseContract.BasePresenter {
        BaseContract.BaseView view;

        BaseMainPresenter(BaseContract.BaseView view) {
            this.view = view;
        }

        @Override
        public void doSomething() {
            if (view != null)
                view.onDoSomething();
        }
    }

    class DemoClass implements BaseContract.BaseView {

        //Create object of Presenter

        /****
         * Example :
         * BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
         */
        @Override
        public void onDoSomething() {
            //Deal with Context here.
        }
    }
</code>
Answer: You could add some "pause" logic to your presenter:

Whenever the UI goes to background, you tell the presenter to "pause" and to save any data being received to a cache (could be as simple as a list inside your presenter).
Whenever the UI is back to foreground, you tell your presenter to unpause and to unload its cache to the UI (if the cache list is not null it pushes it to the UI, just like a regular response received by your interactor)


How to correctly define Accept-Encoding: gzip header in RAML?

Question: I need to describe a REST API  that always returns gzipped response in terms of RAML 1.0 specification.
The API RAML specification must indicate that the API requires the header Accept-Encoding be always sent in the request.
Furthermore, the Accept-Encoding value must be either '*' or 'gzip' or have 'gzip' among other acceptable encodings specified e.g. 'compress, gzip' or 'compress;q=0.5, gzip;q=1.0'.
As a first iteration, I've defined the mandatory header like this:
headers:
  Accept-Encoding:
    type: string
    required: true
    example: 'gzip'

But this, of course, does not indicate that only 'gzip' encoding is supported by the API.
Pls help with defining more detail RAML specification for the 'Accept-Encoding' header.
Answer: RAML doesn't has the expressiveness to validate the values with specific rules. You can set a pattern with a regular expression to restrict the value:
headers:
  Accept-Encoding:
    type: string
    required: true
    example: 'gzip'
    pattern: ^(\*|((.+,)?\s*gzip\s*((,|;).+)?))$

This pattern doesn't guarantee the value will be a valid list but it verifies that it is either only * or gzip standalone or surrounded in either side by commas. You could improve the regular expression to ensure that both sides are comma separated lists, however that kind of validation is outside of what is expected of RAML and belongs in the application code.
Comment: Thanks, this is a best idea so far. I just was hoping that there is more correct way of defining the header parameter as an array with elements separated by comma or semicolon with one mandatory element equal to '*' or 'gzip'
Comment: Why would that be more or less correct as long it is valid by the RAML spec? You probably mean something more specific to this use case. Pattern seems to fit.
Comment: The pattern in the example you provided allows only one value - 'gzip'. While as per the RFC, Accept-Encoding  can be a set of values separated by comma or semicolon. Furthermore, there is a special value '*'  which allows all encodings including gzip so it is valid as well. I've provided some of the examples in the original question. While you can read the RFC (the link in the original question as well) to get more examples.
Comment: I misunderstood that you were asking to restrict to gzip only. The link is good for reference but questions should be self contained. Do you have an actual list of values plus * to accept?
Comment: The standard itself does not restrict the list of the values. But in my case the API needs ONE OF the values in the attribute provided be equal to 'gzip' or '*'.
Comment: Actually, the original question describes the requirement pretty clear imho: "the Accept-Encoding value must be either '*' or 'gzip' or have 'gzip' among other acceptable encodings specified e.g. 'compress, gzip'.
Comment: I updated my answer with a better regular expression and an explanation.
Comment: It could be semicolon as well,, e.g. 'compress;q=0.5, gzip;q=1.0'
Comment: I update the regular expression so that after gzip it could be either a comma or a semicolon


CurrentInputLanguage Property does not update when accessed right after language change

Question: Please look at the code below to better understand what exactly I mean:
using System;
using System.Windows.Forms;

namespace CurrentInputLanguageTest
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Console.WriteLine(InputLanguage.CurrentInputLanguage.LayoutName); // It's US
            Console.ReadLine(); // Changed my keyboard layout while typing something
            Console.WriteLine(InputLanguage.CurrentInputLanguage.LayoutName); // It's still US

            var form = new Form();
            var button = new Button();
            button.Click += CheckInputLanguage;
            form.Controls.Add(button);
            Application.Run(form);
        }

        static void CheckInputLanguage(object sender, EventArgs e)
        {
            // I have changed my input language while the form is opened and pressed the button.
            // It changes when called in this event handler.
            Console.WriteLine(InputLanguage.CurrentInputLanguage.LayoutName);
        }
    }
}

The problem: I have some event handler in my app and I need to know what is current input language when the event is fired. How can I do this?
Answer: The reason it always returns US because you are inside the command and only for that input line is the setting changed.
If the user changes the input language while the form is shown, the current language is properly returned. But you can also programmatically set is with another button:
using System;
using System.Windows.Forms;

namespace CurrentInputLanguageTest
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Console.WriteLine(InputLanguage.CurrentInputLanguage.LayoutName); // It's US
            Console.ReadLine(); // Changed my keyboard layout while typing something
            Console.WriteLine(Application.CurrentInputLanguage.LayoutName); // It's still US

            var form = new Form();
            var grid = new TableLayoutPanel();
            var button = new Button();
            var button2 = new Button();
            button2.Left = button.Right + 5;
            form.Refresh();
            button.Click += CheckInputLanguage;
            button2.Click += ChangeInputLanguage;
            form.Controls.Add(button);
            form.Controls.Add(button2);
            Application.Run(form);
        }

        private static void ChangeInputLanguage(object sender, EventArgs e)
        {
            InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
        }

        static void CheckInputLanguage(object sender, EventArgs e)
        {
            // I have changed my input language while the form is opened and pressed the button.
            // It changes when called in this event handler.
            Console.WriteLine(InputLanguage.CurrentInputLanguage.LayoutName);
        }
    }
}


DBTNG sentence that sums a column from all rows of a specific user and dpm the total

Question: This is my table test_sum_expression with columns:
uid (int) Stores the UID of the user.
points (int) Stores a number.

I have this SQL sentence which SUMS all points from user with uid 1.
SELECT uid, SUM(points) AS total_points
FROM `test_sum_expression`
WHERE uid = 1
GROUP BY UID;

Which produces

How can I produce this same sentence in DBTNG (Database: The Next Generation) format? I mean something like this:
$query = $connection->select('test_sum_expression', 'n')...
I have tried this
$query = $connection->select('test_sum_expression', 'n')
  ->fields('n', ['uid', 'points'])
  ->condition('n.uid', 1, '=')
  ->groupBy('n.uid');
$query->addExpression('SUM(n.points)', 'total_points');
$queryPoints = $query->execute();

dpm($queryPoints);

But without success, it produces $queryPoints Drupal\Core\Database\StatementWrapper#456238 (3). I need to be able to get the total_points.
Answer: $query->execute() returns an object that implements StatementInterface. To get the table columns matching that query you need to either loop over that object or call one of the methods defined from that interface.
Since you are only interested to the sum of the points, I would use the following code.
$query = $connection->select('test_sum_expression')
  ->condition('uid', 1);

$query->addExpression('SUM(points)', 'total_points');

$total_points = $query->execute()->fetchField();

Comment: I am not sure you are referring to the alias associated to the expression. In that case, the alias can be only used in `addExpression()` as in `$select = $this->database->select('node__body', 't'); $select->addExpression('MAX(entity_id)');
$last = $select->execute()->fetchField();`. You can use the alias in `condition()` if the condition needs to check the value of that expression.
Comment: Thanks! Don't forget to declare the alias in the select sentence as it is in the addExpression, it returns an error. I have a question, if I use an alias is it required to use it in the condition and addExpression too?


map, stability of the fixed point, cobweb

Question: Map => $x_{n+1}=\sin x_n$
Show the stability of the fixed point $x^*=0$ is not determined by the linearizatin.
Using the cobweb to show $x^*=0$ is stable.
I took derivative of $\sin x_n$ and put $0$. It said equals to $1$.
Am I wrong or how to solve that?
Comment: You're not wrong. But if derivative equals $1$ you can't determine stability by linearization. In case of mappings you determine stability using eigenvalues of Jacobi matrix. If mapping is hyperbolic at fixed point (i.e., non-zero eigenvalues and no eigenvalues $\lambda$ such that $\vert \lambda \vert = 1$), then linearization tells you everything about stability. So you just have to use cobweb to show stability of $x^{*} = 0$.
Answer:
stability of the fixed point $x^∗=0$ is not determined by the linearization.

This is what you get by observing that the derivative is $1$.

Using the cobweb to show $x^∗=0$ is stable.

You can draw a "cobweb" diagram, but the reasoning contained in it can also be put in words. Suppose the initial point $x_0$ is in the interval $(-\pi/2,\pi/2)$. Within this interval we have $ 0<\sin x < x $ when $x>0$ and $x<\sin x<0$ when  $x<0$. (Consider the positive case; the negative follows by symmetry. Use the fact that $\sin x$ is $\int_0^x \cos t\,dt$.) It follows that  the sequence $x_n$ is monotone and bounded. Hence, it has a limit. The limit must satisfy $x=\sin x$, and the only such point is $0$.


Why is the dot product of two vectors a scalar value?

Question: I'm having some trouble seeing why dot products are said to give scalar values. As a far as I can see, it just gives another vector that is projected onto one of the 2 original vectors. How, then, is the result a scalar quantity. Can someone please explain this to me? Thank you.
Answer: No, it doesn't give another vector. It gives the product of the length of one vector by the length of the projection of the other. This is a scalar.
You may have been misled by some figure.

The dot product is $|A|\,|B|\cos\theta$, not the vector $A'$.
Comment: @EthanChan: as in my answer.
Comment: So it gives the length of A's horizontal length multiplied to the magnitude of B?
Comment: @EthanChan: horizontal is inappropriate here.
Comment: What word would be better for describing Acos(theta) in that case?
Answer: The scalar product describes how an amount of one vector goes in the direction of another.
For example, if you move a set of heavy books on an inclined angle, then there is a horizontal component and a vertical component to the vector describing the force applied.
The scalar product in this case would then describe the amount of force going in the direction of the displacement. The work done here, is defined to be the force exerted multiplied by displacement of the books, the force here is defined to be the force in the direction of the displacement.
Answer: $$(1,2)\cdot (3,4) = 1 (3) + 2(4) = 11$$
is a scalar.
I think you are confusing dot product with projection.
Suppose $u$ is a unit vector, we can project $v$ onto $u$ and its length would be $|u\cdot v|$ while the projection would be $(u\cdot v) u$.
Comment: @EthanChan $A\cdot B$ is the **length** of the projection of $B$ onto $A$. The length of a vector is a scalar.
Comment: It is the length. half of the magnitude of the cross product , $\frac12|A \times B|$ gives the area of the triangle.
Comment: @costrom It's the length. You can remember that because it's largest when the two vectors is colinear (when the area of the triangle is smallest)
Comment: But in all the diagrams I see, the dot product is projected onto one of the vectors. Why is this? (eg: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcStkiJh-1Ijw-2YKX0DzD8DEOjiJ5pomNkIyqEcye38C2Q8iz2goQ).
Comment: @5xum So it treats the second vector as a scalar, and the projects it onto it, to show the length of A⋅B?
Comment: The second vector is also a vector. we have $\vec{A} \cdot \vec{B} = |\vec{A}||\vec{B}|\cos \theta$. In the event that $B$ is a unit vector, then we have $\vec{A} \cdot \vec{B} = |\vec{A}||\cos \theta$ which corresponds to the length of projections if you are familiar with trigonometry.
Comment: @EthanChan No, it takes two vectors and projects one onto the other, and then looks at the length of the resulting vector. That **length** is the scalar product.
Comment: @5xum So we treat that resulting vector as a scalar?
Comment: As shown in the numerical example, $11$ is a scalar and not a vector.
Comment: @EthanChan No. We look at the **length** of the vector. The length of a vector is a scalar.
Comment: @5xum the scalar product is the area of the triangle bounded by the vectors A, B, not the length of the projection of A on B, right?
Comment: @5xum thank you, I was thinking about vector products, clearly :)
Answer: A dot product, by definition, is a mapping that takes two vectors and returns a scalar.
For example, the standard dot product on $\mathbb R^n$ takes two vectors, $x=(x_1,\dots, x_n)$ and $y=(y_1,\dots, y_n)$, and returns their dot product, $$\langle x,y\rangle = \sum_{i=1}^n x_iy_i$$ which is a real number, and thus, a scalar.
Answer: I think it would be easier to start from the basics until we reach to the actual definition of the dot product. Here's my view:
You know the the geometrical definition of multiplication--I'm referring to scalars. The thing I'm referring to is Descartes' geometrical definition of it (just look it up on google images and you'll see what it looks like).
So, if you take the same intuition and apply it on coordinates. Analogously, apply Descartes' definition of multiplication to the two vectors. You may start to notice that the multiplication between the vector looks familiar. It's at this point you should understand that you are now multiplying two lengths together without any regard to the actual coordinates themselves.
This is where projection comes in.
When you project one vector onto another, you have to take into account the unit vector that looms behind descartes' definition, i.e., the reference--really, just think of it as a conversion tool between different units.
Once you get to this point, the projection definition of the dot product is exactly like the cosine definition of it. Once you realize that, the standard component interpretation comes out of the cosine definition.
Also, may not be a tangent, but keep in mind the angle between the vectors is considered only.
So, in a way, the dot product is like the multiplication we already use, but multiplication in a different setting...
So, all in all, from Descartes' intuition of multiplication, you can apply the same logic to coordinates and get a result that seems like it ignores the fact that multiplication is being done on coordinates.
Also, to mention why you get a scalar...I think the dot product is too much like Descartes' description, hence why you get a scalar...
Comment: I am new to advanced mathematics, so I really appreciated the reference to Descarte's geometric definition of mathematics.
Answer: The dot product of two vectors can be considered to be nothing more than a special, simple case of matrix multiplication. This is not immediately obvious because $u\cdot v$ does not look like the multiplication of two matrices, even if we understand that $u=(u_1,u_2)$ and $v=(v_1,v_2)$.
But if we format $u$ and $v$ as a 1×2 and 2×1 matrix respectively (either is a perfectly valid representation of a two-element vector), then we have
$u\cdot v = (u_1,u_2)\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = (u_1v_1+u_2v_2)$.
This is a 1×1 matrix, which is exactly what a scalar is. Thus, a dot product of vectors produces a scalar.


Magento — Top User Swag!

Question:
This has been shipped today! Enjoy your swag, everyone :)
If you still don't have yours and think you should have it by now, please send me an e-mail so I can look into it instead of leaving a comment here. :)

We want to congratulate and thank everyone that helped this site and community grow healthily into what they are today!
If you can find your name among the top 72 users in the first two pages here, we have a surprise for you! We want to send you a token of our appreciation for being among the most prolific users in this community! As such, we're sending you a little box, inside which you'll find:
A T-SHIRT!

STICKERS!

I'll be reaching out to you later today with a link to a form: be sure to fill out the form as soon as you're able to do so! You'll have two weeks to do it, after which I'll close the form and take care of sending all of the swag your way! It should take from 6 to 8 weeks for the package to be delivered to you!
If you're not on the list, don't worry too much about it — we've got some extra swag stored we can send to you for events and such!
Thanks to all of you for making this site great!
Comment: Why doesn't this post have 72 upvotes yet?
Comment: So now the real question - how do we actually verify that you are indeed an employee of SE and not just someone constructing a socially engineered form to collect our addresses?
Comment: You mean you filled the form and were expecting to receive a confirmation e-mail from me, @QaisarSatti? In that case, it's normal that you didn't receive one, 'cause I don't confirm every entry as it goes in ;)
Comment: Aside from me having a diamond next to my name here, @KristofatFooman, you can also find me in [the team page](http://stackoverflow.com/company/team) ;)
Comment: Wooohoo! This is awesome!
Comment: Communities get swag as their designs are rolled out, @BabyinMagento
Comment: My name is Ben, that's mentioned twice on the first page alone (Ben Lessani and Ben Marks) so I should get 2 tshirts right?
Comment: @Ben-Space48. you get to personally deliver the t-shirts to Ben Lessani and Ben Marks
Comment: Ben Marks is never in one country for more than 35 seconds so tracking him down might be difficult, I'll just keep his T shirt for safe keeping.
Comment: Oh wow this is so cool!
Comment: Oh how about top 100? coming from the guy at 92 ;) very cool though either way.
Comment: As I mentioned in the e-mail, @KeyurShah, 6-8 weeks.
Comment: That really awsome & cool. I have thought that i will add this t-shirt at my professional Profile..That must add  some value at my profile  :)
Comment: Hard luck. M on #84.!! wish that was for the users on the third page too.! But am glad to see myself there.! good initiative :)
Comment: It hasn't been shipped yet, @KeyurShah. And it might still take a while, as I mentioned in the e-mail.
Comment: Ahhh lol - I was wondering why some people "received" swag a head of schedule!
Comment: happy to see  my  name on list waiting .... :)
Comment: this is so cool!
Comment: wait is over got  my mail within one hour great speed..
Comment: Awesome !!! That will motivate users
Comment: This is the another motivation tool for me. Thank you.
Comment: This is totally awesome,,happy to see my name....:-)
Comment: This is super cool and motivating. :)
Comment: Awesome ..!  Thank you very much
Comment: Wow!! Thanks :)
Comment: ahhhh i am on 127
Comment: Really nice! I guess they won't be sent (and have arrived) before Meet Magento NL :( @SanderMangel
Comment: Oh no, definitely not, @7ochem :\
Comment: 77th only :-/ Too bad i missed it by 5 places. Any chance the number can be extended ? I like the idea :)
Comment: Thank you, that's very cool!
Comment: @JNat,where the form? am waiting for this?
Comment: @JNat, That's fantastic, but i haven't get any token on my email or where we fill up form?
Comment: I sent out an e-mail about an hour after this post was made. If you can't find the e-mail, look in your spam folders. If it's not there, let me know and I'll send it your way again.
Comment: Yep, check your spam. Found it there as well ;)
Comment: @JNat did not get any confirmation email from you?
Comment: Just confirmed, and I sent it to you, @QaisarSatti. Did you check your spam folder?
Comment: @JNat i am talking about after submitting the form.
Comment: @JNat i just want to know is other stackexchange community users also get shirts ?
Comment: The form doesn't allow Chinese address  :( Please help !
Comment: Won't using a romanized version of the address get to you anyway, @Fra?
Comment: @JNat thank you ... I'll get it deliver in Italy ... I want to be sure it wont get 'lost in translations'  ;)
Comment: Did anyone get t-shirt ? :-)
Comment: Thanks for confimation @JNat Do you have any idea when it will be shipped ?
Comment: While we've been waiting for our MagentoSE shirts to arrive (and had another MageStackDay last Friday/Saturday), some of us decided to wear a fake MagentoSE Shirt @JNat :D Thought this would be fun for you to find out about. See http://magento.stackexchange.com/users?tab=Reputation&filter=all
Comment: My shirt arrived today here in AT. Thanks! :)
Comment: My shirt and stickers arrived weeeeeeeeeeeeee thank you!!!! :) (In Canada)
Comment: Hi @JNat, we did not get any t-shirt  at india.Do you have shipped the t-shirt at india
Comment: We shipped to all the users who filled the form just a week ago, @AmitBera. Please allow for a bit more time for stuff to get to you. If you don't get anything by the end of the month, then please shoot me an e-mail so I can look into it.
Comment: @JNat thanks  4 ur quick reply
Comment: @JNat Thank you I got the t-shirt in India..:)
Comment: @JNat i did not receive any t-shirt in pakistan
Comment: Please shoot me an e-mail, @QaisarSatti, and I'll have a look :)
Comment: Hi, is this "promotion" still active? Would like to have such a shirt too ;)
Comment: Hey @sv3n: this was a one-off thing, as a celebration of the site design launch. We do offer swag to users when they reach 100k reputation points, though :)
Comment: Okay ... just give me another week :P
Comment: OMG! I actually missed my email even though I was among the top 72. I know this is 1+ years old, But still if possible I'd love to have this T-shirt
Comment: @JNat, as you told, you will offer the t-shirt for 100k reputation users, Right now i am having near to 3k. 97k more only to get 100k. Can you please offer me as advance?
Answer: happy to see finally they read my comment
Magento Site Design

Great Response
Your response has been recorded. You can expect your swag to arrive in the next 6 to 8 weeks! Or you can at least hope so... I hope so...

Magento — Top User Swag!


Linear mixed model beta coefficient larger than one

Question: My question is related to the linear mixed model. I have data on the built land area for three sampling sites from which we collected samples for 11 consecutive days. We collected the community of bacteria, algae, and protists using a DNA-based method. Our goal is to examine the relationships among all variables.
Since all of these data have high dimensionality, we used principal component analysis to reduce the dimensionality of each group of data. Subsequently, we used the first axis of each variable to represent the changes in  bacteria, algae, and protists.
Based on ordination analyses, I observed that the data collected from each site were clustered closer together. Therefore, I believe that a mixed model, taking into account the sampling site as a random effect, would be appropriate. Additionally, the diagnostic plot for the independence of samples suggested a pseudo-replication problem arising from the same sampling site. For these reasons, I constructed several linear mixed models using the lmer function from the lme4 package.
However, while diagnosing each individual model, I noticed something that seemed a bit off. The code below illustrates my confusion. So, I built three models as follows:
library(lme4)
library(dplyr)
library(piecewiseSEM)

lme4::lmer(protist1 ~  pro1   +
      (1 | Site) , data = data1) %>% coefs

the estimate of pro1 was 0.4483 while the standardized estimate was 1.3535 ***
lme4::lmer(protist1 ~  algae1   +
         (1 | Site) , data = data1) %>% coefs

the estimate of algae1 was 0.65 while the standardized estimate was 0.899 ***
But when I run the following model:
lme4::lmer(protist1 ~  pro1   + algae1 +
         (1 | Site) , data = data1) %>% coefs

the estimate of pro1 was 0.137 while the standardized estimate was 0.415;
the estimate of algae1 was 0.48 and the standardized estimate was 0.668***
lme4::lmer(protist1 ~  pro1 + algae1   +
         (1 | Site) , data = data1)%>% VIF

the VIF value for pro1 and algae1 was 2.79. which I assumed was okay.
I understood that the standardized estimate can sometimes be larger than one when a model includes multiple predictors, which could be attributed to high collinearity among the predictors, especially in a linear model. However, in this case, the situation was reversed. In the first example, the standardized estimate of pro1 was larger than one, even exceeding the non-standardized estimate, which has left me confused.
From what I understand, the standardized estimate is obtained from scaled data in R, and it is not expected to be larger than +1 or smaller than -1. I might be missing something in the concept of the mixed model, or perhaps using PCA components has an impact on the scaling function and subsequently on the estimates and standard estimates. How can I explain the findings in these models?
dataset
data1 <- data.frame(pro1 = c(13.384, 7.738, 16.957, 13.879, 4.038, 18.585, 15.204, 15.021, 12.217, 14.731, 6.054, -1.077, -0.669, 4.245, -1.841, 0.767, 11.68, 14.147, 11.694, 13.767, 15.845, -16.768,
-18.923, -22.405, -20.059, -19.307, -17.848, -15.305, -17.387, -19.718, -19.168,  -19.477),
algae1 = c(9.73, 2.698, 3.08, 1.885, 3.677, 7.5, 6.923, 7.446, 7.141, 8.472, -2.232, -2.308, -2.178, -4.056, -6.327, -2.901, 7.754, 8.303, 7.983, 5.946, 9.527, -8.026, -8.31, -8.355, -9.927,
-8.161, -6.754, -5.298, -4.841, -5.848, -4.499,  -8.045),
protist1 = c(5.201, 3.667, 2.76, 1.186, 0.976, 6.545, 2.279, 3.279, 2.935, 3.991, 0.104, -0.787,
1.925, -2.069, -4.589, -2.215, 5.698, 7.084, 5.588, 7.445, 8.541, -4.416, -3.863, -6.164, -5.991, -6.039, -6.09, -4.103, -4.023, -5.758, -6.377, -6.719),
Site = c("W1", "W1", "W1", "W1", "W1", "W1", "W1", "W1", "W1", "W1", "W2", "W2", "W2", "W2",
"W2", "W2", "W2", "W2", "W2", "W2", "W2", "W3", "W3", "W3", "W3", "W3", "W3", "W3",
                    "W3", "W3", "W3",  "W3"))

here is the figure of the relationship between pro1 and protist1

and here is the figure of the relationship between algae1 and protist1
Comment: I don't have enough for an answer yet. The short version of the answer is "the relationship (linear regression coefficient based on (y/sd(y)) ~ (x/sd(x)) == corr(y,x) doesn't hold for linear mixed models". I was going to mumble something about "the formula for the univariate regression coefficient, `cov(y,x)/sd(x)`, reduces to  `cor(x,y)` when `sd(x) = sd(y) = 1` when we scale the predictors, but in this case what we're computing is something akin to `lm(r1 ~ pro1)` where `r1` is the residuals from `lm(protist1 ~ Site)`.  That's not **quite** right though ...
Comment: Please edit the question to specify the package that provides `coefs` and `VIF`. Although the example data are very helpful, I can't reproduce all your results without that information about `coefs` and `VIF`.
Comment: sorry, the coefs function is form piecewiseSEM and the VIF function is from semEff package
Comment: In this case (with only three sites) I might recommend a fixed effect of size, and allowing for site-by-covariate interactions: `options(contrasts = c("contr.sum", "contr.poly")); coef(lm(protist1 ~ (pro1*Site), data1_sc))`
Comment: @BenBolker, actually, there are more variables in my study and my goal was to construct a mixed-model-based SEM using piecewiseSEM package and I only want focus on the variation that can be explained by my variables of interest. However, I do not quite get how the model would look when the site was considered a fixed effect in linear model-based SEM. I read from some references that 3 levels of random effect might not be sufficient but with 11 days (replicate) would it still be not okay? and also, is there any concern regarding the coeffcient larger than one  in single predictor mixed model?
Answer: Welcome to the site.  You wrote:

From what I understand, the standard estimate is obtained from scaled
data in R, and it is not expected to be larger than one or smaller
than negative one

AFAIK, this understanding is incorrect. The standard estimate is, indeed, obtained from scaled data, but it does not follow that it should be bounded by -1 and 1. It just means that the parameter estimate is now applied to the scaled data. So, if the standard estimate is (say) 5, that means that the DV goes up by 5 units for each 1 SD increase in the IV.
Comment: Probably. I now see the OP's point, the short answer is "the relationship (linear regression coefficient based on `(y/sd(y)) ~ (x/sd(x)) == corr(y,x)` doesn't hold for linear mixed models", but I'm trying to come up with an explanation now ...
Comment: @BenBolker the OP used the `coefs()` function from the [`piecewiseSEM` package](https://cran.r-project.org/package=piecewiseSEM) to accept the pipe from `lmer()` . That extracts by default standardized coefficients such that "Raw coefficients are scaled by the ratio of the standard deviation of x divided by the standard deviation of y."
Comment: @PeterFlom it was not SE, it was the standardized estimated that was calculated using the 'coefs' function from piecewiseSEM package. So as said before, the standardized estimate was larger than one. I tried to understand this from linear model concept. Isn't the std estimate for one predictor same as the bivariate correlation coefficient? and if so, in linear model, it was impossible to get correlation larger than one. However, I do not quite understand when it is the case of linear mixed model. I guess it is not quite the same but what is the intuitive explanation for that?
Comment: @BenBolker Should we just delete all the comments?


Does a beard adversely affect playing the violin or viola?

Question: It's November which means it's time for "Movember" when some men traditionally grow a moustache in aid of charities aimed at men's health problems, typically prostate and testicular cancers. As moustaches become passe some men are growing a full beard instead.
How does a beard affect your ability to play the violin or viola? I'm particularly concerned about gripping the chin rest when shifting without generating too much tension.
Comment: For me it's kind of the opposite, playing the violin adversely affects growing a beard! In the sense that, in the early stubbly stages, it's a bit painful. I doubt I can blame the violin for my patchy beard.
Comment: In my experience there is not much of an issue apart from it maybe feeling a bit uncomfortable. And if you look at portraits of e.g. Ernst I think it is safe to claim that it works.
Comment: Something you might not have heard is that if your beard is long enough you can roll it up and tuck it under your chin with a hair tie or pin, making a large bushy beard appear very small. Note that this isn't quite the same as tieing a beard. Much like head hair if it's in the way it can be moved out of the way. This might eliminate a lot of the give that you might get. Also lets not forget that some people have hairless soft and supple chins. Wether this impacts violin playing or not I'm not sure, but there are more options than beard or no beard.
Comment: As an aside, if you just grow a moustache it's a non-issue. The point of Movember is to grow a moustache, not a beard or a goatee, because it's supposed to be a conversation starter. A beard doesn't really aid visibility for the cause. The fact that a moustache might be passe for a larger portion of people is part of the reason it was chosen. Also, individual fund raising for charities generally involves some level of hard work or getting out of your comfort zone, to incentivise people donating money to your cause. Essentially you are causing yourself some kind of discomfort for the cause.
Answer: Well, the easy answer is try it and shave it off if it doesn't work! For me, it doesn't work well. It's quite true that you want to avoid tension and that the chin isn't solely responsible for holding the violin up. But I find that the beard is a bit "slippery", where a shaven chin has more friction. You could probably get an idea of the effect by putting a bit of cloth under your chin. It's probably something that could be adapted to quite effectively, just unsettling at first. I also find it a bit prickly and uncomfortable.
You could of course do a soul patch, or perhaps a compact goatee would not interfere with your hold. Or just get into baroque violin, go chinrest-free, and go wild like this guy!
Answer: It really depends on the bulk of the beard. If you have a thick, bushy beard, it could give you a less "positive" hold on the instrument. If you have a short-cropped beard, you may not notice too much. I played viola and never had any issues going from smooth-shaven to a short and stubbly beard.
Beards come in all shapes and sizes as well. You could grow out a full beard to try it, then trim things back to a different shape if needed. A goatee is still a beard.
Oh, the challenges of shoulder-supported instruments! Do you now wish you had taken up cello?
Comment: But you have to lug around a cello and everything costs more =/


Type-generic programming with macros: tricks to determine type?

Question: It's possible to do certain types of type-generic-functions as macros in C, for instance things like:
#define SQRT(x) (sizeof(x) == sizeof(float) ? sqrtf((x)) : \
                 sizeof(x) == sizeof(double) ? sqrt((x)) : \
                 sqrtl((x)) )

This works (mostly) as expected as long as x is a floating point type.
But what if I want a type-generic macro that can take either an integer type or a pointer type, which might have the same size. Is there a clever way to test whether the macro argument is an integer or a pointer? What about an integer versus a floating point type?
Answer: You may detect if an expression is an integer expression or a char* expression, at least on architectures where cast from pointer to uintptr_t is well defined:
#define INT_OR_CHARP(X) (((uintptr_t)((X)+1) - (uintptr_t)(X)) == 1)

This will detect if X is a pointer to a type T with sizeof(T) > 1. This will not work for void* and other corner cases. And because X is evaluated two times you'd have to watch for side effects.
To avoid problems with integer overflow if X is e.g of type signed int you may replace (X) with
(1 ? (X) : (uintmax_t)0)

This guarantees that if X is an integer expression this will be of type uintmax_t. The +1  will then perhaps wrap around, but the result is always well defined and the difference between the two parts will always be 1. If X is a pointer expression, then this is so because any constant integer expression of value 0 is also a null pointer constant.
In total this gives
#define INT_OR_CHARP(X) (((uintptr_t)((1 ? (X) : (uintmax_t)0)+1) - (uintptr_t)(1 ? (X) : (uintmax_t)0)) == 1)

Comment: I don't see how `(1 ? (X) : (uintmax_t)0)` is useful. Is that some sort of trick with the `?:` operator forcing types? Also unsigned types do not overflow.
Comment: @R.: `X` can be of any integer type. So if it were `int`, say, `(X)+1` could overflow. If it is integer type (signed or not) `(1 ? (X) : (uintmax_t)0)` is always of type `uintmax_t` but with value `X`. If `X` is of pointer type that expression will still be of the same pointer type.
Answer: The _Generic keyword was added in the C11 standard for this purpose.
It works like a switch statement for expression types.
Your example can be written using this keyword like this:
#define SQRT(X) _Generic((X), \
    float: sqrtf, \
    double: sqrt, \
    default: sqrtl \
)(X)

GCC provides support for this keyword since version 4.9.
Answer: No. Macros do not know what types are. They perform a literal copy-and-paste of the #define. Type safety simply doesn't exist here.
C is not a strongly typed language in any meaningful sense. If you want some modicum of type safety, use C++, where you can accomplish a little with templates and function overloading.
Comment: Macros don't inherently know, but sometimes there are tricks. For instance, `((0*(x)-1) < 0)` can determine if `x` is signed or not (given that `x` has conversion rank of `int` or higher).
Comment: C++ template parameters are duck-typed just like macros (at least prior to concepts). The error will come from whether the expanded code compiles
Answer: Your result isn't really type-generic, because the result is always long double regardless of what type of argument is passed - the result type of ?: when the second and third operands are arithmetic types is the type that would result from applying the usual arithmetic conversions to those operands.  To make it so, you could use GCC's typeof extension:
#define SQRT(x) (__typeof__ (x))(sizeof(x) == sizeof(float) ? sqrtf((x)) : \
                 sizeof(x) == sizeof(double) ? sqrt((x)) : \
                 sqrtl((x)) )

Integer versus floating-point can also be done using typeof:
(__typeof__ (X))1.1 == 1

I can't think of a way to do integer-versus-pointer.  The techniques described on this page are quite interesting, though.
Answer: It is possible to have some sort of type checking system, but it really is a kludge in C.
glib does this; you can have a look at how they do it, or possibly use it yourself (it's a nifty C library to have around anyway).


How do I use a distribution as an independent variable in a regression?

Question: I'm trying to build a regression model that predicts Trump's vote share in a county in the 2016 election, given demographic data about that county. One of the demographic variables I would like to use is the distribution of income in that county; i.e. the % of people in the county earning <$10k, $10k-20k,etc. If I use the % of people in each bin as an independent variable, then intuitively the coefficient estimates for "nearby" bins would have high collinearity and be prone to overfitting. How do I use the prior knowledge that "%<10k" and "%10k-20k" variables should have a similar (but unknown) effect on Trump vote share in my regression?
Edit: To be clear, I would use n-1 variables to represent n income bins.
Comment: Actually, the collinearity would be perfect since all bins in each county should sum to 100%. Also, welcome to CV!
Comment: Oh I was planning to use n-1 variables for n bins. Should I edit the question to make that clearer?
Answer: You want to use a variable that can be considered as compositional (https://en.wikipedia.org/wiki/Compositional_data). As stated in previous comments there is the issue of collinearity if you try to include all the percentages in the model. There exist possible solutions to this for example using the Additive logratio transform. Interpretation of estimates of parameter regression would slightly difficult however.
I would ask also why do you use those income "bins" as a way to summarize the distribution. If a "complete" distribution is available (for example as census data of income for each subject in the county) you could try different statistics to synthetize the distribution, for example the mean, the median or any other quantile, standard deviation, etc. Each of these summary statistics could be used in your model and check which one performs better.
Comment: Using compositional data techniques doesn't solve the key issue, which is building in the prior knowledge that the coefficients for neighboring bins are similar. Compositional data techniques would work for eg race, where there's no ordering, but they wouldn't work for income as far as I can tell.

Re. "why those bins": as far as I know the census doesn't release the full distribution. You're right that I could use median income as well, but I already know how to do that :) What I'm wondering about is how to use the income bins provided by the census in my regression.
Comment: I guess that similarity between bins arises as consequence of assuming "smooth" distributions (for example unimodal) for income, therefore nearby income bins have similar values. This would lead to the assumption of "nearby bins with similar effects". Also, you are correct pointing out that the compositional data framework ignores the natural ordering of the compositions. I "feel" that this is not very important since the bins are covariates and not the response variable in your model.
Comment: I have made a quick search of compositional data where compositions are ordered, but have not found anything interesting. Perhaps it could be a new field of research in compositional data analysis. Let's wait if there are other more satisfactory answers to your question. However, have you tried this approach (alr transform) in your data?
Comment: I've used an ilr transform for other similar projects, but not for this data set. If I don't get any other answers, I'll probably do that, but I feel like there must be a better way to deal with ordered bins.


Migrate Dimensions

Question: I am trying to migrate to a physical dimensions field with no success. I will prepare the data in prepareRow but before that I was just trying to figure out how it should work. I tried setting default values like this:
<code>$this->addFieldMapping('field_productdimensions')->defaultValue(4);
$this->addFieldMapping('field_productdimensions:width')->defaultValue(1);
$this->addFieldMapping('field_productdimensions:length')->defaultValue(2);
$this->addFieldMapping('field_productdimensions:height')->defaultValue(3);
$this->addFieldMapping('field_productdimensions:unit','cm');
</code>
The above did not insert any data. I also tried with values in prepareRow like this:
<code>    $current_row->dimensions = array(
      'length' => 1,
      'width' => 2,
      'height' => 3,
      'unit' => 'cm'
    );
</code>
All other fields are inserted properly. Any idea what I am doing wrong?
Answer: I figured it out, although it seems weird that width gets the length value, this is how it works in my case. Nothing else was needed in prepareRow function.
<code>    $this->addFieldMapping('field_productdimensions','width');
    $this->addFieldMapping('field_productdimensions:width','length')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:length','length')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:height','height')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:unit','length_units');
</code>
Answer: As I struggeled with this issue today, you actually need to leave out the length mapping, otherwise your migration will fail and all your fields will be empty.
<code>$this->addFieldMapping('field_productdimensions','length')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:width','width')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:height','height')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:unit','length_units')->defaultValue('mm');
</code>
Also note that the value you try to put in is strictly an integer. A value with a space behind it will not work.

Migrate Dimensions


how to load xml data from server in client side using javascript or vbscript?

Question: It's been almost three weeks and I'm Googling around. my eyes got tired and headaches was included too.
I couldn't do it what even 8-10 hours daily computing :(
I have some data that saved in a valid XML file on the server(domain or sub-domain)
I've choosed XML because I'm may or probably need it for other future application use.
What I want to do is:
1- including the XML file and load it on a client side HTML page.(does sub-domain or normal domain make a difference while including?)
2- I do prefer using JavaScript (or Vb Script) or any other client side script(if available) for parsing or manipulating thing.
And If you do prefer me a better way to include a server side XML file including....I'm listening
EDIT:
I'm working on AJAX now but why I can't get data from a URL?
something like:
    xmlhttp.open("GET","https://www.mywebsite.com/xmlfile.xml",true);
buy it's not working :(
Comment: you might need to show us your full AJAX code, what the result is and what you expect to see.
Comment: take a look at [W3Schools AJAX example](http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first) you can see there's an example about getting out data from an XML file which is located on the server.my problem is the URL of requested XML file...I can't show the XML file as text as above example but in client side while the file is **on server** I tried but it was hopeless
Comment: The [file in the example](http://www.w3schools.com/ajax/ajax_info.txt) is not an XML file, it's a text file that contains a HTML snippet `AJAX is not a new programming language.
AJAX is a technique for creating fast and dynamic web pages.`
Comment: are you running your AJAX query across domains? it's likely your browser will not allow this due to security issues
Comment: I know it's not a XML file! it's just a similar way to my problem
I'm using it in Windows 7 sidebar gadget(I think it uses ActiveX object same as IE)
and I request the file from an URL looks something like this `http://www.mywebsite.com/xmlfile.xml` in a regular HTML file that includes AJAX requests same as the link I described above.
Comment: i still think you need to show _your_ code
Comment: I am using **that** code snippet! because I don't have any other idea :( any suggestion or recommending some way is appreciated
Answer:
including the xml file and load it on a client side html page.

Use Ajax, and use a library to access it.

does sub-domain or normal domain make a difference while including?

If it is different to the page: yes
Comment: can I not to use J Query? just using a pure Ajax?
Comment: You don't have to use jQuery, [other libraries are available](http://microjs.com/#ajax). You *should* use a library as (a) there are fiddly differences between browsers to deal with and (b) the syntax to play with XHR directly is ugly.
Comment: well, thanks for both both of you.you've cleared things out for me.Quentin you look you've done a lot's of test and have skills in XHR...what do you recommend to me?
Comment: I don't have any strong preference for any one library over another. jQuery is close to ubiquitous so isn't a bad choice.
Answer: Can you use AJAX? http://www.w3schools.com/ajax/default.asp
Comment: I agree with Quentin about jQuery. It is a good library, but I think it is better for beging to play with XHR directly. It is uglier, but you will learn more.
Answer: Because you haven't given the actual code that you're using, I am guessing here and have put together an HTA that you can try. This only works on Windows (as I believe that is the platform you're targeting). Copy this code into a text file and save it with a .hta file extension:

        <title>HTA Ajax Example</title>

        <input type="button" value="load" onclick="ajaxRequest();"></input>

On clicking the Load button, the text from your w3schools example will be loaded into the page. This should get you started. Should you want to provide a cross-platform solution, a library like jQuery will handle all the differences for you.
As mentioned before, the url used in the request is a full url to a resource on a different server. This won't work if you put this code on a server because of the cross-domain security issue.
If you want to pick up information from an XML file, you might want to use http.responseXML rather than http.responseText. The former property makes the response available as an XML document object rather than a text string.
Comment: I AM using your code now :) and where does HTML application came from?!! :O....thanks Mr...uh.....Oracle certified profession! that's exactly what I want BUT can I use it (or include it) in a regular HTML file?
Comment: you can use this in a regular HTML file, but 1. it's not cross-browser (internet explorer only) and 2. when you put your HTML file on a server, the browser will prevent you from accessing the ajax_info.txt file because it's on a different server. Using AJAX, you can only access resources that reside on the same server  as the one that serves your web page (ie on the same domain)
Comment: yeah I know something about both cross browser and origin policy.but as I mentioned before I just use it locally(client-side) not on the server! I still need to get the data but in a HTML file (not HTA) because Win 7 gadget's only open the HTML file.I tried with HTA but it doesn't function with this file type(only HTML allowed). so is there's anyway? RSS feed's are great but I'm not sure to use it because it's standards.


QQ plot of sigma2 from an MCMC regression?

Question: I've been using R's lm to do some linear regression, but decided to give MCMCregress a try to get a feel for how it works. As expected, I got basically the same coefficients, but the extra sigma2 value puzzles me.
When I do a qqmath plot of the coefficients, I get the following graph, and I'm puzzled by the sigma2 plot. It's obviously not linear, but I'm not sure if that's meaningful in this context. I assume it's sigma squared, and when I took the square root and plotted it, the line was straighter, but still curved.
I guess my question boils down to: what is sigma2 telling me about the MCMC regression fit, and is a graph of it useful or should I ignore the graph and focus on something else? (All of the diagnostics and graphs I've done on my original lm fit seem to indicate that the fit is good, so I'm also wondering if the MCMC regression gives me more information or not.)

(If I need to provide the actual data, I can. I'm hoping that an answer depends more on what sigma2 is rather than on specific values.)
Answer: From the documentation for qqmath it seems that the default behavior is to compare the empirical quantiles to those of a normal distribution. So what the QQ plot for $\sigma^2$ (which is the error variance) is telling you is that its marginal posterior distribution is not normal, which you would fully expect. So it's not really informative or meaningful.
The remaining panels are telling you that the marginal posterior distributions of the regression coefficients are basically normal, perhaps with slightly heavier tails because they are marginalized over $\sigma^2$.
The MCMC regression does give you more information in that you have a full posterior distribution over all the parameters, so you can answer questions like "Given the data I've seen and my prior information, what is the probability that the tempwarmer coefficient is positve". You can also look at joint distributions of two or more parameters, or functions of the coefficients, and on and on.
I should mention that these QQ plots aren't really giving you an indication of goodness of fit. For that you would want to look at some other measures - posterior predictive distributions, for example, or MCMCregress may be able to do formal Bayesian model comparisons for you too. I'm not familiar with that particular function but a cursory Googling turned up some potential leads.
All that said, if the lm() fit is good I wouldn't loose much sleep over it. But I would most wholeheartedly encourage any forays into Bayesian analysis :)
Comment: Thanks! I suspected something like this, based on diagnostics for the (similar) `lm` fit. I'm trying to get my head around MCMC and Bayesian methods and sometimes think I am, then sometimes everything looks trivial, then... I'll pursue what you've said about the full posterior distribution to see where that leads.
Comment: Glad to help. If you're in the market for a reference Gelman and Hill's book Data Analysis Using Regression and Multilevel/Hierarchical Models is a very accessible book to get started, with a lot of practical advice. And it doesn't cost your firstborn child either...
Comment: Good recommendation. I did get that book, but it's interesting how my learning works at this point: I'll go through a book, highlighting and understanding key points, but not getting the bigger picture so I can't really "make it work". Then I move on to another book, another topic, and finally come back around and suddenly it's understandable. Sure enough, I'd highlighted all the right things but somehow it hadn't clicked. Perhaps this time around it will.


on Angular 10, When i have Modal over Modal, BsModalRef hide method hides both popups and leave dark background make App unusable

Question: I have 2 ng-Template and first modal is opening the other one. When I hide the top modal it hides the below one also and only leaves black background and app is unusable, i have to manually refresh the browser. This was working fine before we upgraded to angular 7 to 10.
import { BsModalService , BsModalRef} from 'ngx-bootstrap/modal';

 closeTestPopup1()
  {
    this.modalRef.hide();
  }

  openpopup2(template)
  {
    this.modalRef2 = this.modalService.show(template, { class: 'mrk-def-modal approve-task-modal modal-dialog-centered' });
  }

  closeTestPopup2()
  {
    this.modalRef2.hide();
  }
<ng-template #TestPopup1>

      <button i18n matRipple class="btn btn-secondary btn-sm ml-auto" type="button" (click)="closeTestPopup1()">
        Cancel
      </button>
      <button i18n matRipple class="btn btn-primary btn-sm ml-2 set-s-bg-color"  (click)="openpopup2(TestPopup2)"
        >
        Save
      </button>

  </ng-template>

  <ng-template #TestPopup2>

      <button i18n matRipple class="btn btn-secondary btn-sm ml-auto" type="button" (click)="closeTestPopup2()">
        Cancel popup 2
      </button>
      <button i18n matRipple class="btn btn-primary btn-sm ml-2 set-s-bg-color" type="submit"
        >
        Save
      </button>

  </ng-template>
Comment: This is a (known) issue with newer versions of ngx-bootstrap. Try an older version and it should work again..
Comment: Thanks @MikeOne , its really helpful, I downgraded from 6.1 to 6.0 and it worked, can you please refer e to exact issue link , I couldn't find it.
Comment: i upgraded to 6.2 and it also worked there. Thanks
Answer: it was ngx-bootstrap issue ..upgrading it to latest version fixed it.


What does it mean that "a group is open" on the first pot of the CL group draw?

Question: I know what a group being open means in the later parts of a group draw, normally teams of the same country cannot play in the same group. But I find it very peculiar on the first pot, in other words the first teams to be placed to groups some groups are not "open" to a club. Does that have anything to do with the game schedule Tue/Wed and TV viewership? So that for instance Real Madrid and Barcelona do not play the same day? Or is it a completely different story?
Comment: Hey Posdef, I don't have time to go through this humongous (105 page) [UEFA .pdf](http://www.uefa.com/MultimediaFiles/Download/Regulations/competitions/Regulations/01/79/68/69/1796869_DOWNLOAD.pdf) at the moment, but likely information pertaining to your question is inside... : /
Answer: Teams from the same nation are spread across the two halves of the draw. So if there are 4 English teams, 2 can go in groups A to D and 2 in groups E to H. As such it can cause limitations on other teams.
There are also other limitations, such as the two Manchester clubs must be in the opposite side of the draw to help confirm that they don't play on the same night, this is due to policing laws. It can all get a bit confusing but as a general rule, the first 2 sentences will be enough.
http://www.telegraph.co.uk/sport/football/competitions/champions-league/8721465/Champions-League-group-stage-draw-pots-and-permutations.html for some more help
Answer: This is due to seeding - the top seeds all avoid each other in the first round, in a similar way to other sports such as Tennis.
Here is some more info on the UEFA Champions League
In your example, Real Madrid & Barcelona are both top seeds so cannot meet in the group stages.
Comment: I think you might have misunderstood the question. I am asking of the case when the _first_ teams to be placed into groups. Top 8 teams do not meet each other in the group stages, nothing crazy about that, but when a team cannot be placed into an "empty" group that's peculiar.
Answer: It is basically to do with TV rights and the schedule around that. I can't remember exactly the days (I will edit later) but to use an example:
In England the rights to the group stages are bought on different days. ITV have the rights to Tuesday games (for English teams) whilst Sky have the rights to all Wednesday games. Bearing that in mind, imagine that all English teams are top seeds, now imagine, that Group A and Group B both have a first pick of an English team. The remaining two English clubs are now closed to Group C and Group D because Groups A-D will play on one day and Groups E-H on the other (swapping each game week). This is what is meant by the pot being open or closed. It would be unfair if you had brought the broadcasting rights to Tuesday's games and there were no English clubs playing on the Tuesday.