Is it possible to use Flatgeobuf in Python?

Question: I would like to read from / write to flatgeobuffers from a Python GIS application. My understanding is that this technology can only be used so in JavaScript and TypeScript (of course the compilation stage is language-agnostic insofar as the official CLI does that just fine).
It there a known technique or workaround to read from / write to flatgeobuffers in Python?
Comment: I wrote a simple Python module binding to Rust for this purpose but I would be happy to learn that there's a way to use flatgeobuf natively.
Answer: It appears that Fiona and subsequently Geopandas can read and write FlatGeobuf. GDAL is the backend driver doing the work.


MenuBar problems showing css html

Question: Hello I have some problems on showing my menu bar when I am looking it from laptop or other devices and I was wondering if someone can help me! The problem is whenever I scroll down to the slideshow or where is the video my menu bar disappear behind the slideshow or the video. I think you will understand it perfectly when you try it.

* {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}

/*Menu Bar*/

nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  padding: 0 100px;
  transition: all 300ms;
}

nav.black {
  background: rgba(0, 0, 0, 0.8);
}

nav .logo {
  display: inline-block;
  width: 25%;
  padding: 0 5px;
  line-height: 80px;
  font-size: 24px;
  transition: all 0.3s;
  text-align: center;
}

nav.black .logo {
  color: #fff;
}

nav a {
  display: inline-block;
  width: 12.5%;
  line-height: 80px;
  color: #151515;
  padding: 0 5px;
  text-decoration: none;
  text-transform: uppercase;
  transition: .3s;
  text-align: center;
  vertical-align: top;
}

nav.black a {
  color: #fefefe;
}

nav a:focus {
  outline: none;
}

nav a.active {
  background: #E2472F;
  color: #fff;
  border-radius: 6px;
}

section.sec1 {
  width: 100%;
  height: 100vh;
  background: url(img/lol.jpg);
  background-size: cover;
  background-position: center;
}

/* Hamburger icon */

.hamburger {
  display: none;
  cursor: pointer;
}

.hamburger .bar1,
.hamburger .bar2,
.hamburger .bar3 {
  width: 35px;
  height: 5px;
  background-color: #fefefe;
  margin: 6px 0;
  transition: all 0.4s;
}

.openMenu .hamburger .bar1 {
  -webkit-transform: rotate(-45deg) translate(-9px, 6px);
  transform: rotate(-45deg) translate(-9px, 6px);
}

.openMenu .hamburger .bar2 {
  opacity: 0;
}

.openMenu .hamburger .bar3 {
  -webkit-transform: rotate(45deg) translate(-8px, -8px);
  transform: rotate(45deg) translate(-8px, -8px);
}

/*Media*/

@media(max-width: 860px) {
  nav {
    background: rgba(0, 0, 0, 0.8);
    padding: 0 20px;
    color: #fefefe;
    overflow: hidden;
  }
  .logo {
    position: fixed;
    top: 0;
  }
  nav a {
    width: 100%;
    line-height: calc((100vh - 80px) / 6);
    transform: translateY(80px);
    visibility: hidden;
  }
  .openMenu a {
    color: #fefefe;
    visibility: visible;
  }
  .hamburger {
    display: inline-block;
    position: absolute;
    right: 20px;
    top: 20px;
  }
  .openMenu {
    height: 100vh;
  }

  .slider {
    width: 100%;
    height: 23%;
  }
  section.sec1 {
    width: 100%;
    height: 30%;
  }
  article#video{
    width: 100%;
  }
  video{
    width: 100%;
  }
  aside{
   border-bottom:#e8491d 3px solid;
   width: 100%;
   height: 250px;
}
aside#welcometext{
  font-family: cursive;
  width: 100%;
  height: 76%;
}
aside#New{
  font-family: serif;
  height: 100%;
  width: 100%;
}
}

/*Slideshow*/
*{
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  }

.slider {
  overflow: hidden;
  height: 450px%;
}

.slider figure div{
  width: 20%;
  float: left;
}

.slider figure img{
  width: 100%;
  float: left;
}

.slider figure{
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  animation: 25s slidy infinite;
}

@keyframes slidy{
   0% {
      left: 0%;
   }
   10% {
      left: 0%;
   }
   12% {
      left: -100%;
   }
   22% {
      left: -100%;
    }
   24% {
      left: -200%;
   }
   34% {
      left: -200%;
   }
   36% {
      left: -300%;
   }
   46% {
      left: -300%;
   }
   48% {
      left: -400%;
   }
   58% {
      left: -400%;
   }
   60% {
      left: -300%;
   }
   70% {
      left: -300%;
   }
   72% {
      left: -200%;
   }
   82% {
      left: -200%;
   }
   84% {
      left: -100%;
   }
   94% {
      left: -100%;
   }
   96% {
      left: 0%;
   }
}

/*Welcome*/

article{
  float: left;
  margin: 0 auto;
  width: 23%;
  height: auto;
}

#welcometext{
  float: right:
  margin: 0 auto;
  width: 100%;
  height: auto;
  border-bottom:#e8491d 3px solid;
  height: 38%;
}

#News1{
  margin-left: 5%;
  width: 52%;
  height: 7%;
  display: inline-flex;
}

section.News{
  border-bottom:#e8491d 3px solid;
  height: 100%;
}

aside#New{
  padding: 27%;
  height: 100%;
  width: 100%;
  font-family: cursive;

}

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie-edge">
  <title> Landschaft </title>
  <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700,900' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="style.css">

  <link rel="stylesheet" href="https//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Landschaft
НАЧАЛОСЪБИТИЯПЪТЕКИФОРУМВРЪЗКИВХОД

    <video width="295" height="238" controls autopl>
      <source src="video.mp4" type="video/mp4">
        </video>

Welcome

Lamium (dead-nettles) is a genus of about 40–50 species of flowering plants in the family Lamiaceae,[3] of which it is the type genus. They are all herbaceous plants native to Europe, Asia, and northern Africa, but several have become very successful weeds of crop fields and are now widely naturalised across much of the temperate world.[2][4][5]

 dsadas das

Answer: Adding a z-index rule to your nav element solved the problem on my end.
nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  padding: 0 100px;
  transition: all 300ms;
  z-index: 100;
}

Here is a little read on the subject
Answer: Give your header/nav a z-index:
nav {z-index:100}

Z-index positions your content in front-back space. The higher the value the closer to the front the element will be.

MenuBar problems showing css html


Parallel lines and corresponding angles.

Question:
In the figure shown, a,b and c are measures of the three angles and RQ is parallel to NO and PQ is parallel to MN.

Quantity A: a
Quantity B: b+c

Options:

Quantity A is greater than Quantity B
Quantity B is greater than Quantity A
Quantity A is equal to Quantity B
Relationship Cannot be determined

How to quickly visualize and solve this?
Answer is C i.e. Both are equal
Answer: The angle $c$ is equal to the angle $P\hat RQ$. So, $c+b+R\hat PQ=180^\circ$. But $a+R\hat PQ=180^\circ$ too and therefore $a=b+c$.


Expressing every function as sum of an odd and an even function

Question: If $f$ is to be written as a sum of the even function $E$ and the odd function $O$,
$E=\dfrac{f(x) + f(-x)}{2} \quad$ and
$O=\dfrac{f(x)-f(-x)}{2}$
obviously works.
I get a bit confused though because in a previous question I was asked to investigate if the sum of two functions $g$ and $h$ is even, odd or neither depending on if $g$ and $h$ is even or odd. I came to the conclusion that (with the subscript denoting if function is even or odd) $g_e(x) + h_o(x) $ is neither even nor odd assuming no function is the zero function:
$k(x) = g_e(x) + h_o(x) \implies k(-x) = g_e(-x) + h_o(-x) = g_e(x) - h_o(x) \quad$($k$ not even)
$k(x) = g_e(x) + h_o(x) \implies -k(-x) = -g_e(-x) - h_o(-x) = -g_e(x) + h_o(x)\quad$($k$ not odd)
So does the two facts:
1.) The sum of an even function $g_e$ and an odd function $h_o$ is neither even nor odd unless $g_e(x)=0$ or $h_o(x)=0$.
2.) Any function, even, odd or netheir, can be written as the sum of an even and an odd function.
mean that $E(x)=0$ or $O(x)=0$ if $f$ is even or odd?
Or am I just totally wrong about everything.
Comment: You got everything right!
Answer: You are actually right. However, it would be better to add something to fact number 2:
Every function can be written uniquely as the sum of an even function and an odd function.
Another way to say the same thing (using linear algebra terminology) is: The vector space consisting of functions $\mathbb{R}\to\mathbb{R}$ is the direct sum of the space of even functions and the space of odd functions.
Answer: The function $k(x)=0$ statistifies both $k(x)=-k(-x)$ and $k(x)=k(-x)$, so it is even and odd. This is the only function that is both even and odd.
If $f$ is originally even or odd, substituting the even or odd definition will give you that $O(x)=0$ or $E(x)=0$.


Which is a better way to check if an array has more than one element?

Question: I just need to check if an array has more than one element.
I am trying to do it this way :
if (isset($arr['1']))

the other traditional way is
if (sizeof($arr)>1)

Which of the two is better? In such situaions, how should I judge between two alternate methods?
Is there any performance check meter available to measure which is better?
Comment: Assumption here is $arr is validated for an array already! That means, before it comes to this if condition check, its already checked if its an array.
Comment: http://phparraylength.com/
Answer: Use this
if (sizeof($arr) > 1) {
     ....
}

Or
if (count($arr) > 1) {
     ....
}

sizeof() is an alias for count(), they work the same.
Edit:
Answering the second part of the question:
The two lines of code in the question are not alternative methods, they perform different functions. The first checks if the value at $arr['1'] is set, while the second returns the number of elements in the array.
Comment: @N.B.: The question was edited, the initial code was `if (sizeof($arr))`, which translated to `if (sizeof($arr) == 1)` - clearly that doesn't check if the array has **more than one** element. This answer is correct, and I see no reason to down-vote, hence my upvote.
Comment: I'll admit that I didn't take a look at the original version of the question, which this answer is a reply to. The context is different, and I apologize for labelling the answer as wrong. It's not wrong, if you look at the original question. It's bad for the edited question.
Comment: The second code snippet in the question will check if the value at $arr['1'] is set or not, it is not concerned about the count. This was not addressed in the answer, just thought I'd mention this and hope the author of the answer will update the answer :).
Comment: @AndersM. thanks for pointing that out. I've reflected it in the answer.
Comment: I don something like :
 for index in 0..<3
        {
            guard let testTop:Prediciton = topPredictions[index] else
            {
                //your default object

            }
            predictionResult.append(testTop)
        }

in swift 4
Answer: if(is_array($arr) && count($arr) > 1)
Just to be sure that $arr is indeed an array.
sizeof is an alias of count, I prefer to use count because:

1 less character to type
sizeof at a quick glance might mean a size of an array in terms of memory, too technical :(
Comment: From the manual: *Returns the number of elements in var. **If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned***.
Comment: @AlixAxel hmm, but if $arr is a string, count($arr) would return character count of that string so ya
Comment: No, if `$arr` is a string, it'll return `1`.
Comment: @AlixAxel oh ok... wow thanks, didn't know that :o... In any case I'm just gonna leave it there in case OP wants to differentiate between a String and Array (regardless of size) Thanks for pointing that out :)
Answer: if (count($arr) >= 2)
{
  // array has at least 2 elements
}

sizeof() is an alias for count(). Both work with non-arrays too, but they will only return values greater than 1 if the argument is either an array or a Countable object, so you're pretty safe with this.
Answer: Obviously using count($arr) > 1 (sizeof is just an alias for count) is the best solution.
Depending on the structure of your array, there might be tons of elements but no $array['1'] element.
Answer: Use count()
if (count($my_array) > 1) {
// do
}

this page explains it pretty well http://phparraylength.com/
Answer: I prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages. Many programmers expect sizeof() to return the amount of memory allocated.
Comment: Also explained here.  http://stackoverflow.com/questions/3974385/php-array-count-or-sizeof

This is valuable since this question is now a top Google hit for `sizeof` vs `count`
Answer: For checking an array empty() is better than sizeof().
If the array contains huge amount of data. It will takes more times for counting the size of the array. But checking empty is always easy.
//for empty
  if(!empty($array))
     echo 'Data exist';
  else
     echo 'No data';

 //for sizeof
 if(sizeof($array)>1)
      echo 'Data exist';
 else
    echo 'No data';

Answer: isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains
Answer: I assume $arr is an array then this is what you are looking for
if ( sizeof($arr) > 1) ...

Answer: The first method
if (isset($arr['1']))
will not work on an associative array.
For example, the following code displays "Nope, not more than one."
$arr = array(
    'a' => 'apple',
    'b' => 'banana',
);

if (isset($arr['1'])) {
    echo "Yup, more than one.";
} else {
    echo "Nope, not more than one.";
}

Answer: I do my array looping and getting filled defaults accordingly in Swift 4/5
   for index in 0..<3
    {
        let isIndexValid = allObjects.indices.contains(index)
        var yourObject:Class = Class()
        if isIndexValid { yourObject = allObjects[index]}
        resultArray.append(yourObject)
    }


How to update the status automatically after 15 days?

Question: I have a date and status column in a MySQL table. currently status of post is = Sent/Received. All i want to change the status = Aborted after 15days automatically.
Query:
 if (txtrecdate.Text == "" && ddlstatus.SelectedItem.Text != "Completed")
     {
         queryStr = "update barter_proposals set website_a=?web_a,email_id=?email,email_id2=?email2,email_id3=?email3,contact_name=?cname,proposal_status=?status,reason=?rsn," +
              "comment1=?com1 ,agreement=?agreement,agrmt_filename=?agrmt_filename,comment2=?com2,comment3=?com3,lifespan_date=?lpdate where pro_id=?pro_id";
     }

I googled it and found this solution:
UPDATE table SET status = "Aborted" where date=DATE_ADD(date, INTERVAL 15 DAY)

How to apply this in my update query? Is there any other way to change the status automatically after 15 days?
Comment: write a sql job and run it daily. Check for the date which is 15 days old from sysdate, for such a data, update the status as Aborted. If you do not want that in sql, do that in either in a windows service or azure web job or task scheduler. You can look at Hangfire as well
Comment: Well, if you want to do that in  _"C#"_ level, you have several options, i.e. create service which will execute your code when time comes or use Windows Task Scheduler.
Comment: Or you can also create a function wherein if the user logged in/ visit the system, the function will check the date. If the date is over 15 days then update the status, if not then do nothing.
Answer: Look into MySQL events. First of all you'll need to turn on event scheduler on MySQL side
https://dev.mysql.com/doc/refman/5.7/en/events-configuration.html
and then create event
delimiter $$

CREATE EVENT update_table_statuses
    ON SCHEDULE
      EVERY 1 DAY STARTS '2018-03-22 23:00:00'
    DO
      BEGIN
        UPDATE table SET status = "Aborted" where date=DATE_ADD(date, INTERVAL 15 DAY);
      END $$

delimiter ;

Event will be executed once a day
Comment: i dint understand where condition.what it will do? date=DATE_ADD(date, INTERVAL 15 DAY)
Comment: Heh, well the query inside event was copied from your question. Perhaps you've meant `date = date_sub(now(), interval 15 day)` but who knows
Comment: yup @alexey ...actually i am doing changes on live server...so i just wanted to confirm it whether that condition update the status after 15 days..
Comment: your original won't do anything as it's always false, the one above should do the trick. also I would replace `=` with `<=`


makefile with variable target

Question: I'm attempting to define a Makefile that will take in a filename (eg. foo) as a variable from the command line, and then compile & link using gcc.
So if I type   make foo   it will compile foo.c  ,link up foo.o to the required libraries, and clean up the .o file. Here's my code so far, does anyone have any suggestions for where I'm going wrong?
<code>@: $@.o
        @echo target is $@
        gcc $@.o -v -lmar -lbar -DDEBUG -o $@
        rm $@.o

$@.o: $@.c
        gcc -c -v $@.c
</code>
Answer: Make already uses the arguments as the target list.  And it already has implicit rules that do what you want.  You should be able to get away with something like this as your makefile:
<code>LDLIBS=-lmar -lbar
LDFLAGS=-v
CFLAGS=-v
</code>

makefile with variable target


Alocação estoura memória em função recursiva em C

Question: Criei um programa que fica alocando de 4 em 4 bytes de memória sucessivamente através de uma função recursiva:
<code>#include <stdio.h>
#include <stdlib.h>
#define BUF 2

void overflow(int payload){
    payload = payload - 1;
    int stack = (int)malloc(payload * sizeof(int));
    payload = payload + 1;
    overflow(payload);
}

int main(void){
    overflow(BUF);
    return 0;
}
</code>
Acontece que ele para de funcionar antes de conseguir consumir toda a memoria isto seria algum tipo de controle do própio Windows para garantir a integridade do sistema ou é erro de programação mesmo?
Como eu poderia contornar isso e deixa o programa consumindo memoria até o topo e quando chegar ao topo parar de alocar memoria?
Estou usando windows 7 64 bits
Comment: Acredito que o seu problema pode ser estouro de pilha, devido a várias recursões envolvidas. Me parece que o tamanho padrão é de 1 Mbytes: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686774(v=vs.85).aspx
Comment: Parar de funcionar você quer dizer que ele fecha sozinho? Aparece alguma mensagem se executar via CMD?
Comment: sim, ele so consegue alocar ate uns 90% da memoria e para
Comment: Tá, mas vc só respondeu "sim" ... Eu fiz **duas** perguntas, eu não sei se o sim foi pra primeira ou pra segunda. Então ele fecha sozinho? Sim ou não? Tentou rodar o teu programa chamando/compilando via CMD? Por exemplo: `c:\Users\projeto>g++ meu.cpp -o meu.exe && meu.exe`. Se tentou que mensagem de erro aparece no momento que ele finaliza?
Comment: não me retorna nenhum erro na compilação esse codigo esta funcional me parece que algo relacionado a linguagem mesmo estrutura de dados alocação dinamica e tal ele executa normal mas quando chega nos 90% para de alocar memoria e o windows cancela a execução do programa
Comment: Tem antivirus no teu PC?
Comment: Aqui deu este problema: https://i.stack.imgur.com/iolXN.png
Comment: @GuilhermeNascimento não tem antivirus só o windows defender que esta ativado
Comment: acho que o problema estava na recursão mesmo eu coloquei dentro de um while e funcionou
Comment: Está usando qual versão do mingw? Pra eu poder testar.
Comment: @GuilhermeNascimento 6.3.0
Answer: É erro de programação e estouro da pilha porque a recursão não tem fim. Se mudou para um laço e funcionou, é porque o laço tem uma condição que o encerra, caso contrário não teria fim, ainda que não haveria estouro de pilha. Mas em algum momento longínquo estouraria o heap também.
<code>#include <stdio.h>
#include <stdlib.h>
#define BUF 2

void *overflow(int payload) {
    if (--payload) {
        int *stack = malloc(payload * sizeof(int));
        overflow(payload);
    }
}

int main(void) {
    overflow(BUF);
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @Assanges não lembro porque coloquei no retorno, eu acho que foi sem querer, não tem necessidade não. `malloc()` retorna um ponteiro, então a variável que vai receber tem que ser um ponteiro. Tem compilador que aceita um ponteiro ser jogado em um inteiro, mas isso não costuma ser adequado.
Comment: por que você colocou no retorno da função void um ponteiro e declarou um ponteiro na variável stack? não entendi.
Answer: Tente com o seguinte código, retirado de uma resposta no StackOverflow em inglês:
<code>main() {
  int Mb = 0;
  while ( malloc(1<<20)) ++Mb;
  printf("Allocated %d Mb total\n", Mb);
}
</code>
(Declare stdio e stdlib para este exemplo)
Comment: Infelizmente, acredito que não responde a pergunta o post.
Comment: eu fiz dentro de um while e funcionou como o esperado travou minha maquina precisei reiniciar executem por conta e risco
`#include
#include

int main(void){
    while(1){
        int stack = (int)malloc(1 * sizeof(int));
    }
    return 0;
}
`


HP 4101: scan-to-email without Digital Sending software?

Question: Word on the street (well, forums) is that the HP 4101 can scan-to-email without the expensive Digital Sending Suite/software: I've read that you can just set the SMTP gateway and away you go.
However it doesn't appear to be that simple, at least that I can see from the manual and/or from the settings.  I'm not on-site at the moment and can't recall exact errors, but it doesn't send, and complains about not finding or incorrect digital sending settings, even though I've added the SMTP gateway to the configuration.
I telnet'ed into the SMTP server and sent some test messages, so there's nothing wrong with the mail server's config.
Any ideas?
Answer: Ended up being a flaky JetDirect card.


Meu programa dá erro quando o valor do array é null

Question: Tenho um programa que retira relatórios de um sistema, estou incluindo mais uma tabela no programa.
Os dados que são lidos, vem de um array mas as vezes ele está vazio, e quando dá isso o programa dá erro.
Coloquei um if para verificar se a variável está null, pois se estiver ele pegará o valor de outra tabela.
Mas quando debuguei ele acusou erro:

Source not found

JSONObject js2 = js.getJSONObject("cliente").getJSONArray("enderecoList").getJSONObject(0);

nessa linha e o programa para de rodar.
for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject js = jsonArray.getJSONObject(i);
            JSONObject js2 = js.getJSONObject("cliente").getJSONArray("enderecoList").getJSONObject(0);
            JSONObject js3;
                if (js2 == null){
                    js3 = js.getJSONObject("unidade").getJSONObject("municipio");
                } else {
                    js3 = js2.getJSONObject("municipio");
                }

Answer: Não sei se poderá ser isso mas existe um método próprio do JSON para verificar se o valor está a NULL. O método é o isNull();
Por exemplo:
if(jsonObject.isNull("parentId")){
   jsonObject.put("parentId", 0);
}

Comment: Tentei utilizar o metodo, mas ele aponta que é incompativel e que é necessario uma variavel do tipo String.
Answer: Boa tarde, você pode usar a propriedade has para validar se o existe o atributo dentro do json.
Segue:
    JSONArray jsonArray = null;

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject js = jsonArray.getJSONObject(i);
            JSONObject js3;

            if (js.has("unidade")) {
                JSONObject unidadeJson = js.getJSONObject("unidade");
                if (unidadeJson.has("municipio")) {
                    js3 = unidadeJson.getJSONObject("municipio");
                }
            }

            if (js.has("cliente")) {
                JSONObject jsonClient = js.getJSONObject("cliente");
                if (jsonClient.has("enderecoList") && !jsonClient.isNull("enderecoList")) {
                    JSONArray enderecoArray = jsonClient.getJSONArray("enderecoList");
                    if (enderecoArray.length() > 0) {
                        JSONObject js2 = enderecoArray.getJSONObject(0);
                        if (js2.has("municipio")) {
                            js3 = js2.getJSONObject("municipio");
                        }
                    }
                }
            }
      }


Basketball Under Push

Question: While the opponent is shooting a ball, is it legal to push the Basketball through under the ring before it completely enters the Ring, to prevent a Shoot?
Answer: No, it is not legal
What you seem to be describing is a violation known as Goaltending.  Touching the ball when it is in or over the ring is a violation and the opposing team is awarded the points associated with the shot.
The relevant ruling states:

Section I—A Player Shall Not:
i. Touch the rim, net or ball while the ball is in the net, preventing it from clearing the basket.
PENALTY: If the violation is at the opponent's basket, the offended team is awarded two points, if the attempt is from the two point zone and three points if it is from the three-point zone. The crediting of the score and subsequent procedure is the same as if the awarded score has resulted from the ball having gone through the basket, except that the official shall hand the ball to a player of the team entitled to the throw-in. If the violation is at a team's own basket, no points can be scored and the ball is awarded to the offended team at the free throw line extended on either sideline. If there is a violation by both teams, no points can be scored, play shall be resumed by a jump ball between any two opponents in the game at the center circle.
Comment: Does every single simple rule that can be looked up in 10 seconds deserve a question and answer?
Comment: @Coach-D Is it off-topic?  Does this SE site get a ton of other high quality questions?  Is there a relevant duplicate? Feel free to vote to close the question if you have an issue but I see no reason to suppress the already limited activity further on this stack.

Basketball Under Push


Multiple paired t-tests. Bonferroni number of comparisons?

Question: I have done 9 paired t-tests, to see if there are significant changes in pre and post measurements of three variables (FFMQ-SF, GSE, WEMWBS), across three groups (Engagement level: minimum, medium, maximum). See the attached table.
I believe that to protect from Type 1 errors, I must conduct a bonferroni correction in which the critical significance level of .05 is adjusted. Question 1: Do I need to do this?
To perform a Bonferroni correction, one should divide the critical p-value by the number of comparisons being made. But I don't know whether I should divide 0.05 by 3 or by 9. I conducted 9 t-tests, but 3 for each scale/group. Question 2: what is the correct option?
Question 3: Finally, am I correct in thinking that I should convert my p-values into adjusted p-values by multiplying by either 3 or 9?
Answer: Question 1: Yes and no. Yes, you should account for multiple testing but you do not have to use the Bonferroni correction. The Bonferroni correction is easy to apply but known to be very conservative - meaning that it often will not detect non-zero effects even though there are non-zero effects.
The Holm procedure is slightly more powerful than the Bonferroni correction and works under the same set of assumptions.
In addition, there are a number of Bootstrap based "step-down methods" that can be even more powerful. These methods use simulation techniques to find out about the correlation of the tests.
In your case, you may have some prior information about the correlation of the tests. For example, if groups are independent then applying a test to three different groups gives three independent tests. You can use that.
Question 2: 9 for the Bonferroni correction that you are suggesting.
Question 3: I find it best to report the unadjusted p values and only change the significance indicator (the "stars"). This way the reader has all the information to apply, for example, Holm instead of Bonferroni.
Comment: Thank you Andreas. The Holm-Bonferroni correction was suitable for me. For anyone else reading who wants to know how to do it, I found the following two resources helpful:                       http://www.talkstats.com/threads/how-to-present-data-after-holm-bonferroni-correction.40049/               https://stat.ethz.ch/education/semesters/ss2012/ams/slides/v8.2.pdf


What's the best way to create variables that are available to every single URL on my site, based on node id or taxonomy id?

Question: On Drupal site A we have a bunch of links to non-Drupal site B. For marketing and tracking purposes all these links have a different URL variable appended to them, so that when a user registers on site B we can determine where on site A they came from.
At the moment I use page.tpl.php to create the variable ($forceCode) but it now transpires I need this variable to be available to node.tpl.php too, and I feel like there must be a less hacky and more universal way of doing this, probably using a preprocess function in template.php that right now seems beyond my comprehension level.
PLAIN LANGUAGE EXPLANATION
$specialPages is an array of node IDs that need a special code.
$specialFolders is an array of taxonomy IDs that need a special code.

If the current node ID matches any in the nid array, I set the variable accordingly.
If not then I get the category (taxonomy) of the current node, or if the current page is a taxonomy term itself then use its own tid.

Then using this taxonomy ID I get all other tids that are parents of that tid.
Then I look for matches of any of these taxonomy IDs in my array of special tids in order to set the variable.

If the current page has not matched any of my special nodes or taxonomies, the variable remains its default value.

ACTUAL CODE
// we later restrict our parent taxonomy search to certain types but it's not strictly necessary
$contentTypes = array("article","advpoll","event");

$specialFolders = array(
    276 => "events",
    292 => "free-dating",
    498 => "date-explorer"
);
$specialPages = array(
    22 => "reviews",
    86 => "texting"
);

$forceCode = "default";

// check for specific page first
if (@array_key_exists($node->nid,$specialPages)){
    $forceCode = $specialPages[$node->nid];
} else {
    // there was no entry for this nid, let's check parent terms
    $parentTerms = array();
    $hasParents = false;
    if (arg(0) == "taxonomy") $hasParents = arg(2);
    if (@in_array($node->type,$contentTypes)) {
        $category = field_view_field('node', node_load($node->nid), 'field_category');
        $hasParents = $category['#items'][0]['tid'];
    }
    if ($hasParents !== false) {
        $parents = taxonomy_get_parents_all($hasParents);
        foreach ($parents as $term){
            $parentTerms[] = $term->tid;
        }
    }

    foreach ($parentTerms as $tid){
        if (array_key_exists($tid,$specialFolders)){
            $forceCode = $specialFolders[$tid];
            continue;
        }
    }
}

Comment: Are you looking for the generic [`hook_preprocess()`](https://api.drupal.org/api/drupal/modules%21system%21theme.api.php/function/hook_preprocess/7) perhaps?
Comment: Perhaps Clive - I've tried messing with it for an hour since you said that but not got far. I've tried:

    `function hook_preprocess(&$variables, $hook){
      $variables['myNewVar'] = "anything";
    }`

has not lead to me being able to access $myNewVar from either page.tpl.php or node.tpl.php on any type of page. Also tried by prefixing function with themename.
Answer: I've found a very satisfactory solution using function matchtheme_preprocess(&$variables, $hook) which will always supply variables to page and node templates.
The more complicated bit was finding an appropriate way to get this function to collect the data I need (nid or tid) properly regardless of whether it was the page or node template making the call.
Essentially (this is the cut down version) I just did this:
if ($hook == "page"){
    // supplies variables to page.tpl.php
    // the page template can cover anything, including a node and taxonomy
    if (arg(0) == "node"){
        $nidToCheck = arg(1);
    } else if (arg(0) == "taxonomy"){
        // already a taxonomy page, the term id is the category
        $hasParents = arg(2);
    }
} else if ($hook == "node"){
    // supplies variables to node.tpl.php
    $nidToCheck = $variables['elements']['#node']->nid;
}

From there if ($nidToCheck) allows me to use the nid to generate $hasParents for nodes, and then I can move on handling all nodes and taxonomy terms to do what I want (all this bit is essentially the same as in my question).
Finally I feed back to the template an array of variables in much the same way as they were set before.
So glad to have this sorted as it caused quite a headache. Would love to hear whether or not this is an efficient or clever way of dealing with it. The most obvious issue to me is that the array of variables (and of course the whole function) will get run twice on node pages - once for the page template and once for the node template - which is a touch inefficent. I guess I could contain the whole thing in an if (!isset...


Facebook FBML fb:board troubles

Question: I followed the tutorial on the Facebook dev site and used the following code to create a discussion app. Whenever I click on "Start new Topic" nothing happens. I've searched and found people with similar issues but no one found a solution. Anyone have any idea?
<code><fb:board xid="crockrec_board"
      canpost="true"
      candelete="false"
      canmark="false"
      cancreatetopic="true"
      numtopics="5"
      returnurl="http: //facebook.com/CrockpotRecipes/">
</code>
Community Recipes

Answer: As you said, there are many problems with this, it's not only you. Even official test console is throwing errors for me. Fill bug report on their page
Answer: I would consider abandoning any FBML markup like this. FBML is not going to be supported after January 2012 (in about a month) and in June 2012 FBML markup just isn't going to work at all, so anything you write in it now is going to have to be rewritten. Might as well find the alternative now rather than later.

Facebook FBML fb:board troubles


BASIC programming language getting variable

Question: On MSX BASIC 2.1, I get this error when compiling my basic code.
10 Input "Your name", U$
run
Syntax Error
OK

Why is this syntax incorrect?
Comment: That might depend on which version of BASIC you are using.
Comment: Version 2.1 is what I'm using
Comment: Version 2.1 of which BASIC product?
Comment: It might actually matter.
Comment: Based on a quick Google search, it looks like the comma might need to be a semicolon (http://www.atarimagazines.com/creative/v10n2/204_Simple_screen_graphics_wi.php ).
Comment: That did the trick! Yay!
Comment: Traditionally in BASIC, the semicolon `;` has been used to separate the text of the input prompt from the input variable, whereas commas usually are used to separate multiple variables. The original Dartmouth BASIC allowed multiple variables from the beginning, like this:
Answer: It is possible that you may need INPUT in upper case and the semicolon.  Try the following.
10 INPUT "Your name"; U$

Comment: A semicolon `;` was the delimiter between the prompt string and the variable name for this command in the original Dartmouth BASIC (1964) and the earliest versions of line numbered BASIC.
Answer: It looks like you need to use a semicolon instead of a comma (See the use of the INPUT command on this page for example)


zip_code makes location inaccurate

Question: I'm using this library (just a wrapper) to work with google geocode api
I discovered that in some cases, result returned for almost same addresses - the only difference is including/omitting zipcode - is different.
example:
<code>import googlemaps
gmaps = googlemaps.Client(key="secret")

addr_w_zip = "23 Commonwealth Avenue, Chestnut Hill, MA 02467, US"
addr_no_zip = "23 Commonwealth Avenue, Chestnut Hill, MA, US"

res_w_zip = gmaps.geocode(addr_w_zip)
res_no_zip = gmaps.geocode(addr_no_zip)

# these are the results I get:
# with zip: 42.340062300, -71.167352500
# no zip: 42.340072600, -71.167537600
# coordinates where zip is used are incorrect (building next to the correct one)
</code>
Am I missing something or should be zip code omitted to get more accurate results ? Or should it be used only if substantial part of search query address is missing (like city and state)?
EDIT:
Any tips, best practices and gottchas are also welcome.
Comment: It looks like performing the [request with the zip code](https://maps.googleapis.com/maps/api/geocode/json?&address=23%20Commonwealth%20Avenue%2C%20Chestnut%20Hill%2C%20MA%2002467%2C%20US) produces a result of type "street_address" whereas the [request without the zip code](https://maps.googleapis.com/maps/api/geocode/json?&address=23%20Commonwealth%20Avenue%2C%20Chestnut%20Hill%2C%20MA%2C%20US) produces a result of type "premise". So Google is storing both requests as separate entities unfortunately.
Comment: [Without a postal code](https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D23%2520Commonwealth%2520Avenue%252C%2520Chestnut%2520Hill%252C%2520MA%252C%2520US) you get place ID `ChIJvSgFdl1444kRU7OhpzwJ-I8`, but [with postal code](https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D23%2520Commonwealth%2520Avenue%252C%2520Chestnut%2520Hill%252C%2520MA%252002467%252C%2520US) you get place ID `EjQyMyBDb21tb253ZWFsdGggQXZlbnVlLCBDaGVzdG51dCBIaWxsLCBNQSAwMjQ2NywgVVNBIhoSGAoUChIJTVLln11444kR_uxpXjGKZukQFw` (interpolated). It sounds like a bug.
Answer: With zip code:
https://geocoder.ca/23%20Commonwealth%20Avenue%2C%20Chestnut%20Hill%2C%20MA%2002467%2C%20US

CHESTNUT HILL, MA » 23 COMMONWEALTH, CHESTNUT HILL, MA » 02467-1099 » 42.340075,-71.167546

23 COMMONWEALTH AVE, CHESTNUT HILL, MA 02467-1099 ( 02467-1099 polygon ) Confidence Score: 1

Without zip:
https://geocoder.ca/23%20Commonwealth%20Avenue%2C%20Chestnut%20Hill%2C%20MA

CHESTNUT HILL, MA » 23 COMMONWEALTH, CHESTNUT HILL, MA » 02467-1099 » 42.340075,-71.167546
23 COMMONWEALTH AVE, CHESTNUT HILL, MA 02467-1099 ( 02467-1099 polygon ) Confidence Score: 1

Both rooftop results.

zip_code makes location inaccurate


React-Native - Using a Javascript Module that relies on node.js core module

Question: I'm trying to utilize a vcard parsing module written in Javascrip but it relies on node.js core modules, fs and path.  My application is written in React-Native.  Does anyone have any recommendations as to how I can emulate the file-system and path modules of npm for use inside the vcard parsing javascript module?
The file in question is the index file of vcards-js and is located inside my node_modules folder of my application.  So app/node_modules/vcards-js/index.js
var fs = require('fs');
var path = require('path');

Comment: Look at browserify.
Comment: React Native is not running on Node, it's running on a pure Javascript environment, not only node API won't work, many Web API does not work either.
Answer: I forked vCards JS for use with React Native: https://github.com/idxbroker/vCards-js/tree/react-native
Instead of trying to emulate fs one to one, I use a package: react-native-fs
Which has very similar methods and functionality as the Node equivalent.
vCards JS only required minimal adjustments.
Feel free to use this version.
npm install react-native-vcards@https://github.com/idxbroker/vCards-js.git#react-native --save

Comment: It's funny you mention this because it's something I've actually already tried but couldn't quite get it to work @Daniel IDXBroker.  FYI there is no directory at reart-native-vcards.  If you have a working version, I would love to use yours
Comment: Sorry, we changed the repo name right after I posted this. I updated the original post to reflect the new repo location.


What is the joint probability distribution of two same variables

Question: Let $f\left(x\right)$ be the probability density function of the
random variable $X$. What is the joint probability distribution of
$f_{X,Y}\left(x,y\right)$ if $Y=X$?
Thanks for any helpful answer.
Comment: **Hint:** $f(x,y) = f(y|x) \cdot f(x)$. Now, for a fixed $x$, what must the conditional density $f(y|x)$ look like?
Comment: Right, so $f(x,y) = 0$ when $x \neq y$. What about when $x=y$?
Comment: It seems like a Dirac delta function, right?
Comment: @Macro Please help in this related question [Conditioning on probability zero: Can we say $P(B \le A|B=b) = P(b \le A|B=b)$?](https://stats.stackexchange.com/questions/515364/conditioning-on-probability-zero-can-we-say-pb-le-ab-b-pb-le-ab-b)
Answer: $X$ is not jointly continuous with itself in the sense that there is no joint density
function (pdf) $f_{X,X}(s,t)$ that has positive value over a region of positive area
in the plane
with coordinate axes $s$ and $t$.  All the probability mass lies on the straight line of slope $1$ through the origin (a region of zero area) and the joint cumulative
probability distribution
function CDF is
$$F_{X,X}(s,t) = P\{X \leq s, X \leq t\} = P\{X \leq \min(s,t)\} = F_X(\min(s,t)).$$
As whuber points out in the comments on another answer,
$\frac{\partial^2F_{X,X}(s,t)}{\partial s\partial t}$ is not
defined for $s=t$.
Comment: Dilip Sarwate, please help in this related question [Conditioning on probability zero: Can we say $P(B \le A|B=b) = P(b \le A|B=b)$?](https://stats.stackexchange.com/questions/515364/conditioning-on-probability-zero-can-we-say-pb-le-ab-b-pb-le-ab-b)
Answer: $F_{(X,X)}(t,s) = P[X \le t,X \le s] = P[X \le \inf(s,t)]$
$f(s,t) = \frac{ \partial ^2F_{(X,X)}}{\partial s \partial t}(t,s) =  \frac{\partial^2 (P[X \le t] \Large{1_{\{s=t\}}})}{\partial^2  t } $
Where
$\frac{\partial  \Large{1_{\{s=t\}}}}{\partial t}$
$= lim_{\sigma \mapsto 0} \frac{1}{\sqrt{2\sigma \pi}} e^{\frac{-s^2}{\sigma^2}}$
More info about the indicator function derivation are here
Comment: What does that second line mean?  How do you justify the two equalities? How do you even make sense of the last expression (the indicator function is not differentiable)?
Comment: $f$ is pdf and $F$ is the cdf. Maybe I missed something but : I consider case $s\not= t$ where the derivative is zero, and the other case where $s= t$ where it is not. In other words, I do not differentiate the indicator.
Comment: I see. Nevertheless, your manipulations do not appear to be correct. For example, let $X$ have a uniform distribution. Your conclusion is that $f(s,t)$ is identically zero, which is obviously false. One of the problems is clear: $F(t,s)$ is not differentiable where $s=t$.
Comment: Yes yes, my mistake: If everything apart from the derivative is clear, then yes  we do need to differentiate the indicator function wrt to $t$, the result will the delta function ( the result can be represented as a mathematical limit (of a gaussian when its variance tends to zeo,  , more info are here : http://en.wikipedia.org/wiki/Dirac_delta_function)
Answer: Random Discrete Variables Case:
For Y=X,
then pij = 0 as xi and Xj are always exclusive
for i=j and pij=pi for i=j. as xi and xi to happen in the same time has pi chance.
So E[X^2] = E[XX] = Sum (xi^2*pi) for both cases
Comment: Please use proper math formatting, see http://stats.stackexchange.com/editing-help#latex. The current answer is incomprehensible (for example, what are "xi" and "Xj" in "xi and Xj are always exclusive for i=j"?)  Though I don't think this answers the question in any case, as it is rather clear from the notation and wording that $X$ was intended to be continuous.
Comment: Dan and @JuhoKokkala , please help in this related question [Conditioning on probability zero: Can we say $P(B \le A|B=b) = P(b \le A|B=b)$?](https://stats.stackexchange.com/questions/515364/conditioning-on-probability-zero-can-we-say-pb-le-ab-b-pb-le-ab-b)


Confused by Derivation of Regression Function

Question: I just got a copy of The Elements of Statistical Learning by Hastie, Tibshirani, and Friedman. In chapter 2 (Overview of Supervised Learning) section 4 (Statistical Decision Theory), he gives a derivation of the regression function.

Let $X \in \mathbb{R}^p$ denote a real valued random input vector, and $Y\in\mathbb{R}$ a real valued random output variable, with joint distribution $Pr(X,Y)$. We seek a function $f(X)$ for predicting $Y$ given values of the input $X$. This theory requires a loss function $L(Y,f(X))$ for penalizing errors in prediction, and by far the most common and convenient is squared error loss: $L(Y,f(X))=(Y −f(X))^2$. This leads us to a criterion for choosing $f$,
$$\begin{align*} EPE(f) &= E(Y-f(X))^2 \\ &= \int [y - f(x)]^2Pr(dx, dy)\end{align*}$$ the expected (squared) prediction error.

I completely understand the set up and motivation. My first confusion is: does he mean $E([(Y - f(x))]^2)$ or $(E[(Y - f(x))])^2$? Second, I have never seen the notation $Pr(dx,dy)$. Can someone who has explain its meaning to me? Is it just that $Pr(dx) = Pr(x)dx$? Alas my confusion does not end there,

By conditioning on $X$, we can write $EPE$ as $$\begin{align*}EPE(f) = E_XE_{Y|X}([Y-f(X)]^2|X)\end{align*}$$

I am missing the connection between these two steps, and I am not familiar with the technical definition of "conditioning". Let me know if I can clarify anything! I think most of my confusion has arisen from unfamiliar notation; I am confident that, if someone can break this derivation down into plain English, I'll get it. Thanks stats.SE!
Answer: For your first confusion, it should be Expectation of squared error, so it is $E[(Y-f(x))^2].$
For the notation of $Pr(dx,dy)$, it is equal to $g(x,y)\,dx\,dy$, where $g(x,y)$ is the joint pdf of x and y. And $Pr(dx)=f(x)\,dx$, this can be interpreted as the probability of x being within a tiny interval of $[x,x+dx]$ is equal to pdf value at the point $x$, i.e. $f(x)$ times the interval length $dx$.
The equation about the EPE stems from the theorem $E(E(Y|X))=E(Y)$ for any two random variables $X$ and $Y$. You can prove this by using the conditional distribution. The conditional expectation is the expectation calculated using the conditional distribution. The conditional distribution $Y|X$ means the probability of $Y$ after you know something about $X$.
In our case, suppose we denote the squared error as a function $L(x,y)=(y-f(x))^2$, the EPE is calculating
$$\begin{equation}\begin{split}E(L(x,y))&=\int\int L(x,y)g(x,y)dx\,dy \\
&=\int\bigg[\int L(x,y)g(y|x)g(x)dy\bigg]dx \\
&=\int\bigg[\int L(x,y)g(y|x)dy\bigg]g(x)dx \\
&=\int\bigg[E_{Y|X} (L(x,y)\bigg]g(x)dx \\
&=E_X(E_{Y|X} (L(x,y)))\end{split}\end{equation}$$
The outcome of above corresponds to the result you listed. Hope this can help you a bit.
Comment: For the final result after conditioning, the book also has the |X, while the final result of this answer is missing it. Is it important?


How do I create a new logic brick for blender?

Question: I am thinking of making a new logic brick to contribute or 10, but need to get a template/idea of where to start, I want to make a 6dof actuator and sensor first, that can trigger based on rotation targets or distance limits etc, and a actuator that can remove or change a 6dof target to a new position or object and position,
I am making a open source 3d puzzle game with limited ads in game, but need to make a few logic bricks, for me and the community....
Answer: There are no coding tutorials regarding BGE Game logic that I'm aware of, but here are some pointers for the code:
The game logic parts are mostly in:
https://svn.blender.org/svnroot/bf-blender/trunk/blender/source/gameengine/GameLogic/
You'll see that sensors implement the ISensor interface. Browse through a few different sensors to see how they work. Blender has NDOF device support, so NDOF events already exist (get handled by our GHOST layer: https://svn.blender.org/svnroot/bf-blender/trunk/blender/intern/ghost/intern/GHOST_NDOFManager.h ). You could create a new manager like the mouse manager (see the gamelogic directory for the different managers ).
With this information you should be able to get started. Read the existing code carefully, you'll be able to find what you need.
Answer: You can use this commit Mouse actuator commit as your template to add a new actuator.


How to straighten unneeded turns in a A* graph search result?

Question: I have been working on a JavaScript implementation of the early 90's adventure games and specifically plotting a path from the place the hero is standing to the location the player has clicked on.  My approach is to first determine if a strait line (without obstructions) can be drawn, if not then to search for a path of clear way-points using Brian Grinstead's excellent javascript-astar.  The problem I'm facing however is the path (while optimal will veer into spaces that would seem to the user an unintended.  Here is a classic example of what I'm talking about (the green path is the generated path, the red dots are each turns where the direction of the path changes):

Now I know that A* is only guaranteed to return a path that cannot be simpler (in terms of steps), but I'm struggling to implement a heuristic that weights turns.  Here is a picture that show two other paths that would also qualify as just as simple (with an equal number of steps)

The Blue path would present the same number of steps and turns while the red path has the same number of steps and fewer turns.  In my code I have a simplifyPath() function that removes steps where the direction changes, so if I could get all possible paths from astar then I could select the one with the least turns, but that's not how A* fundamentally works, so I'm looking for a way to incorporate simplicity into the heuristic.
Here is my current code:

var img,
    field = document.getElementById('field'),
    EngineBuilder = function(field, size) {
        var context = field.getContext("2d"),
            graphSettings = { size: size, mid: Math.ceil(size/2)},
            engine = {
                getPosition: function(event) {
                    var bounds = field.getBoundingClientRect(),
                        x = Math.floor(((event.clientX - bounds.left)/field.clientWidth)*field.width),
                        y = Math.floor(((event.clientY - bounds.top)/field.clientHeight)*field.height),
                        node = graph.grid[Math.floor(y/graphSettings.size)][Math.floor(x/graphSettings.size)];

                    return {
                        x: x,
                        y: y,
                        node: node
                    }
                },
                drawObstructions: function() {
                    context.clearRect (0, 0, 320, 200);
                    if(img) {
                        context.drawImage(img, 0, 0);
                    } else {
                        context.fillStyle = 'rgb(0, 0, 0)';
                        context.fillRect(200, 100, 50, 50);
                        context.fillRect(0, 100, 50, 50);
                        context.fillRect(100, 100, 50, 50);
                        context.fillRect(0, 50, 150, 50);
                    }
                },
                simplifyPath: function(start, complexPath, end) {
                    var previous = complexPath[1], simplePath = [start, {x:(previous.y*graphSettings.size)+graphSettings.mid, y:(previous.x*graphSettings.size)+graphSettings.mid}], i, classification, previousClassification;
                    for(i = 1; i < (complexPath.length - 1); i++) {
                        classification = (complexPath[i].x-previous.x).toString()+':'+(complexPath[i].y-previous.y).toString();

                        if(classification !== previousClassification) {
                            simplePath.push({x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid});
                        } else {
                            simplePath[simplePath.length-1]={x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid};
                        }
                        previous = complexPath[i];
                        previousClassification = classification;
                    }
                    simplePath.push(end);
                    return simplePath;
                },
                drawPath: function(start, end) {
                    var path, step, next;
                    if(this.isPathClear(start, end)) {
                       this.drawLine(start, end);
                    } else {
                        path = this.simplifyPath(start, astar.search(graph, start.node, end.node), end);
                        if(path.length > 1) {
                            step = path[0];
                            for(next = 1; next < path.length; next++) {
                                this.drawLine(step, path[next]);
                                step = path[next];
                            }
                        }
                    }
                },
                drawLine: function(start, end) {
                    var x = start.x,
                        y = start.y,
                        dx = Math.abs(end.x - start.x),
                        sx = start.x<end.x ? 1 : -1,
                        dy = -1 * Math.abs(end.y - start.y),
                        sy = start.y<end.y ? 1 : -1,
                        err = dx+dy,
                        e2, pixel;

                    for(;;) {
                        pixel = context.getImageData(x, y, 1, 1).data[3];
                        if(pixel === 255) {
                            context.fillStyle = 'rgb(255, 0, 0)';
                        } else {
                            context.fillStyle = 'rgb(0, 255, 0)';
                        }
                        context.fillRect(x, y, 1, 1);

                        if(x === end.x && y === end.y) {
                            break;
                        } else {
                            e2 = 2 * err;
                            if(e2 >= dy) {
                                err += dy;
                                x += sx;
                            }
                            if(e2 <= dx) {
                                err += dx;
                                y += sy;
                            }
                        }
                    }
                },
                isPathClear: function(start, end) {
                    var x = start.x,
                        y = start.y,
                        dx = Math.abs(end.x - start.x),
                        sx = start.x<end.x ? 1 : -1,
                        dy = -1 * Math.abs(end.y - start.y),
                        sy = start.y<end.y ? 1 : -1,
                        err = dx+dy,
                        e2, pixel;

                    for(;;) {
                        pixel = context.getImageData(x, y, 1, 1).data[3];
                        if(pixel === 255) {
                            return false;
                        }

                        if(x === end.x && y === end.y) {
                            return true;
                        } else {
                            e2 = 2 * err;
                            if(e2 >= dy) {
                                err += dy;
                                x += sx;
                            }
                            if(e2 <= dx) {
                                err += dx;
                                y += sy;
                            }
                        }
                    }
                }
            }, graph;
            engine.drawObstructions();
            graph = (function() {
                var x, y, rows = [], cols, js = '[';
                for(y = 0; y < 200; y += graphSettings.size) {
                    cols = [];

                    for(x = 0; x < 320; x += graphSettings.size) {
                        cols.push(context.getImageData(x+graphSettings.mid, y+graphSettings.mid, 1, 1).data[3] === 255 ? 0 : 1);
                    }
                    js += '['+cols+'],\n';
                    rows.push(cols);
                }
                js = js.substring(0, js.length - 2);
                js += ']';
                document.getElementById('Graph').value=js;
                return new Graph(rows, { diagonal: true });
            })();
            return engine;
        }, start, end, engine = EngineBuilder(field, 10);

field.addEventListener('click', function(event) {
    var position = engine.getPosition(event);
    if(!start) {
        start = position;
    } else {
        end = position;
    }
    if(start && end) {
        engine.drawObstructions();
        engine.drawPath(start, end);
        start = end;
    }
}, false);
#field {
border: thin black solid;
    width: 98%;
    background: #FFFFC7;
}
#Graph {
    width: 98%;
    height: 300px;
    overflow-y: scroll;
}

Click on any 2 points on white spaces and a path will be drawn
<canvas id='field' height

='200' width='320'></canvas>
<textarea id='Graph' wrap='off'></textarea>

After digging into Michail Michailidis' excellent answer I've added the following code to my simplifyPath() function) (demo):
simplifyPath: function(start, complexPath, end) {
    var previous = complexPath[1],
        simplePath = [start, {x:(previous.y*graphSettings.size)+graphSettings.mid, y:(previous.x*graphSettings.size)+graphSettings.mid}],
        i,
        finalPath = [simplePath[0]],
        classification,
        previousClassification;

    for(i = 1; i < (complexPath.length - 1); i++) {
        classification = (complexPath[i].x-previous.x).toString()+':'+(complexPath[i].y-previous.y).toString();

        if(classification !== previousClassification) {
            simplePath.push({x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid});
        } else {
            simplePath[simplePath.length-1]={x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid};
        }
        previous = complexPath[i];
        previousClassification = classification;
    }

    simplePath.push(end);
    previous = simplePath[0];
    for(i = 2; i < simplePath.length; i++) {
        if(!this.isPathClear(previous, simplePath[i])) {
            finalPath.push(simplePath[i-1]);
            previous = simplePath[i-1];
        }
    }
    finalPath.push(end);

    return finalPath;
}

Basically after it reduces redundant steps in the same direction, it tries to smooth out the path by looking ahead to see if it can eliminate any steps.
Comment: From what I understood your simplifyPath checks just two edges and not more than those .. so this algorithm is not correct you have to check for two edges, three edges, ... till the length of the whole path for it to work. Probably there is a better algorithm than this one up there O(2^N) but certainly not with O(N) like yours which is using the basic heuristic of just checking contiguous edges.
Answer: Very very intresting problem! Thanks for this question! So...some observations first:
Not allowing diagonal movement fixes this problem but since you are interested in diagonal movement I had to search more.
I had a look at path simplifying algorithms like:
Ramer Douglas Peuker
(http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm)
and an implementation: https://gist.github.com/rhyolight/2846020.
I added an implementation to your code without success. This algorithm doesn't take into account obstacles so it was difficult to adapt it.
I wonder what would the behavior be (for diagonal movements) if you had used Dijkstra instead of A* or if you used an 'all shortest paths between a pair of nodes' algorithm and then you sorted them by increasing changes in direction.
After reading a bit about A* here http://buildnewgames.com/astar/ I thought that the implementation of A-star you are using is the problem or the heuristics. I tried all the heuristics on the a-star of your code including euclidean that I coded myself and tried also all the heuristics in the http://buildnewgames.com/astar code Unfortunately all of the diagonal allowing heuristics were having the same issue you are describing.
I started working with their code because it is a one-to-one grid and yours was giving me issues drawing. Your simplifyPath that I tried to remove was also causing additional problems. You have to keep in mind that since
you are doing a remapping this could be an issue based on that

On a square grid that allows 4 directions of movement, use Manhattan distance (L1).
On a square grid that allows 8 directions of movement, use Diagonal distance (L∞).
On a square grid that allows any direction of movement, you might or might not want Euclidean distance (L2). If A* is finding paths on the grid but you are allowing movement not on the grid, you may want to consider other representations of the map. (from http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html)

What is my pseudocode algorithm:
var path = A-star();
for each node in path {
    check all following nodes till some lookahead limit
    if you find two nodes in the same row but not column or in the same column but not row {
       var nodesToBeStraightened = push all nodes to be "straightened"
       break the loop;
    }
    skip loop index to the next node after zig-zag
}

if nodesToBeStraightened length is at least 3 AND
   nodesToBeStraightened nodes don't form a line AND
   the resulting Straight line after simplification doesn't hit an obstruction

       var straightenedPath =  straighten by getting the first and last elements of nodesToBeStraightened  and using their coordinates accordingly

return straightenedPath;

Here is the visual explanation of what is being compared in the algorithm:
Visual Explanation:

How this code will be used with yours (I did most of the changes - I tried my best but there are so many problems like with how you do drawing and because of the rounding of the grid etc - you have to use a grid and keep the scale of the paths accurate - please see also assumptions below):
    var img,
    field = document.getElementById('field'),
    EngineBuilder = function(field, size) {
        var context = field.getContext("2d"),
        graphSettings = { size: size, mid: Math.ceil(size/2)},
        engine = {
            //[...] missing code
            removeZigZag: function(currentPath,lookahead){
                //for each of the squares on the path - see lookahead more squares and check if it is in the path
                for (var i=0; i<currentPath.length; i++){

                    var toBeStraightened = [];
                    for (var j=i; j<lookahead+i+1 && j<currentPath.length; j++){
                        var startIndexToStraighten = i;
                        var endIndexToStraighten = i+1;

                        //check if the one from lookahead has the same x xor the same y with one later node in the path
                        //and they are not on the same line
                        if(
                           (currentPath[i].x == currentPath[j].x && currentPath[i].y != currentPath[j].y) ||
                           (currentPath[i].x == currentPath[j].y && currentPath[i].x != currentPath[j].x)
                        ) {
                            endIndexToStraighten = j;

                            //now that we found something between i and j push it to be straightened
                            for (var k = startIndexToStraighten; k<=endIndexToStraighten; k++){
                                toBeStraightened.push(currentPath[k]);
                            }
                            //skip the loop forward
                            i = endIndexToStraighten-1;
                            break;
                        }
                    }

                    if (toBeStraightened.length>=3
                        && !this.formsALine(toBeStraightened)
                        && !this.lineWillGoThroughObstructions(currentPath[startIndexToStraighten], currentPath[endIndexToStraighten],this.graph?????)
                        ){
                        //straightening:
                        this.straightenLine(currentPath, startIndexToStraighten, endIndexToStraighten);
                    }
                }
                return currentPath;
            },

            straightenLine: function(currentPath,fromIndex,toIndex){
                for (var l=fromIndex; l<=toIndex; l++){

                    if (currentPath[fromIndex].x == currentPath[toIndex].x){
                         currentPath[l].x = currentPath[fromIndex].x;
                    }
                    else if (currentPath[fromIndex].y == currentPath[toIndex].y){
                         currentPath[l].y = currentPath[fromIndex].y;
                    }
                }
            },

            lineWillGoThroughObstructions: function(point1, point2, graph){
                var minX = Math.min(point1.x,point2.x);
                var maxX = Math.max(point1.x,point2.x);
                var minY = Math.min(point1.y,point2.y);
                var maxY = Math.max(point1.y,point2.y);

                //same row
                if (point1.y == point2.y){
                    for (var i=minX; i<=maxX && i<graph.length; i++){
                        if (graph[i][point1.y] == 1){ //obstacle
                            return true;
                        }
                    }
                }
                //same column
                if (point1.x == point2.x){
                    for (var i=minY; i<=maxY && i<graph[0].length; i++){
                        if (graph[point1.x][i] == 1){ //obstacle
                            return true;
                        }
                    }
                }
                return false;
            },

            formsALine: function(pointsArray){
                //only horizontal or vertical
                if (!pointsArray || (pointsArray && pointsArray.length<1)){
                    return false;
                }

                var firstY = pointsArray[0].y;
                var lastY = pointsArray[pointsArray.length-1].y;

                var firstX = pointsArray[0].x;
                var lastX = pointsArray[pointsArray.length-1].x;

                //vertical line
                if (firstY == lastY){
                    for (var i=0; i<pointsArray.length; i++){
                        if (pointsArray[i].y!=firstY){
                            return false;
                        }
                    }
                    return true;
                }

                //horizontal line
                else if (firstX == lastX){
                    for (var i=0; i<pointsArray.length; i++){
                        if (pointsArray[i].x!=firstX){
                            return false;
                        }
                    }
                    return true;
                }
                return false;
            }
            //[...] missing code
        }
        //[...] missing code
    }

Assumptions and Incompatibilities of the above code:

obstacle is 1 and not 0
the orginal code I have in the demo is using array instead of {x: number, y:number}
in case you use the other a-star implementation, the point1 location  is on the column 1 and row 2.
converted to your {x: number, y:number} but haven't checked all the parts:
I couldn't access the graph object to get the obstacles - see ?????
You have to call my removeZigZag with a lookahead e.g 7 (steps away) in the place where you were
doing your path simplification
admittedly their code is not that good compared to the a-star implementation from Stanford but for our purposes it should be irelevant
possibly the code has bugs that I don't know of and could be improved. Also I did my checks only in this specific world configuration
I believe the code has complexity O(N x lookahead)~O(N) where N is the number of steps in the input A* shortest path.

Here is the code in my github repository (you can run the demo)
https://github.com/zifnab87/AstarWithDiagonalsFixedZigZag

based on this A* Javascript implementation downloaded from here: http://buildnewgames.com/astar/

Their clickHandling and world boundary code is broken as when you click on the right side of the map the path calculation is not working sometimes. I didn't have time to find their bug. As a result my code has the same issue
Probably it is because the map I put from your question is not square - but anyway my algorithm should be unaffected. You will see this weird behavior is happening if non of my remove ZigZag code runs. (Edit: It was actually because the map was not square - I updated the map to be square for now)
Feel free to play around by uncommenting this line to see the before-after:
result = removeZigZag(result,7);

I have attached 3 before after image sets so the results can be visualized:
(Keep in mind to match start and goal if you try them - direction DOES matter ;) )
Case 1: Before

Case 1: After

Case 2: Before

Case 2: After

Case 3: Before

Case 3: After

Case 4: Before

Case 4: After

Resources:

My code (A* diagonal movement zig zag fix demo): https://github.com/zifnab87/AstarWithDiagonalsFixedZigZag
Original Javascript A* implementation of my demo can be found above (first commit) or here: - http://buildnewgames.com/astar/
A* explanation: http://buildnewgames.com/astar/
A* explanation from Stanford: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
JavaScript A* implementation used by OP's question (Github):
Ramer Douglas Peuker Algorithm (Wikipedia): http://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Javascript implementation of Douglas Peuker Algorithm: https://gist.github.com/rhyolight/2846020
A* Algorithm (Wikipedia): http://en.wikipedia.org/wiki/A*_search_algorithm
Comment: Here is the code using a scene from KQ3 :) http://jsfiddle.net/sperske/q7er3sy7/ (and you can load in your own images (as Data URIs)
Comment: Thanks :) What I suggest is use your one grid on top of that but your paths should be precise to the pixel level for this to work. I don't see why this is not a general approach for any grid that has these properties and doesn't distort the original grid ;). If you have to do it in a distorted grid we will be talking about problems found in Computational Geometry. Something that could involve academic paper reading etc. I believe your application is quite smaller to need something that is not a perfect grid :)
Answer: You can use a modified A* algorithm to account for changes in direction. While simplifying the result of the standard A* algorithm may yield good results, it may not be optimal. This modified A* algorithm will return a path of minimal length with the least number of turns.
In the modified A* algorithm, each position corresponds to eight different nodes, each with their own heading. For example, the position (1, 1) corresponds to the eight nodes
(1,1)-up, (1,1)-down, (1,1)-right, (1,1)-left,
(1,1)-up-left, (1,1)-up-right, (1,1)-down-left, and (1,1)-down-right
The heuristic distance from a node to the goal is the the heuristic distance from the corresponding point to the goal. In this case, you probably want to use the following function:
H(point) = max(abs(goal.xcor-point.xcor), abs(goal.ycor-point.ycor))
The nodes that correspond to a particular position are connected to the nodes of the neighboring positions with the proper heading. For example, the nodes corresponding to the position (1,1) are all connected to the following eight nodes
(1,2)-up, (1,0)-down, (2,1)-right, (0,1)-left,
(0,2)-up-left, (2,2)-up-right, (0,0)-down-left, and (2,0)-down-right
The distance between any two connected nodes depends on their heading. If they have the same head, then the distance is 1, otherwise, we have made a turn, so the distance is 1+epsilon. epsilon represents an arbitrarily small value/number.
We know need to have a special case for the both the start and goal. The start and goal are both represented as a single node. At the start, we have no heading, so the distance between the start node and any connected node is 1.
We can now run the standard A* algorithm on the modified graph. We can map the returned path to a path in the original grid, by ignoring the headings. The total length of the returned path will be of the form n+m*epsilon. n is the total length of the corresponding path in the original grid, and m is the number of turns. Because A* returns a path of minimal length, the path in the original grid is a path of minimal length that makes the least turns.
Comment: @MichailMichailidis The heading at any node is explicitly accounted for by splitting each position into eight position-heading pairs. My heuristic is admissible because it is the minimal distance between any two points in the grid, where the distance to any adjacent node is of length 1. Every path in the original grid corresponds to exactly one path in the modified graph, where the path in the modified graph is at least as long as the path in the original grid, and only equal if it has no turns. I will try to code a demo as soon as I have time, it might make things a bit clearer.
Comment: Now having a more thorough look in your algorithm. How will you weight your distance and change direction heuristics for each of the steps of the algorithm?? Usually G (cost) is very short-sighted and it is constant based on the type of movement (e.g diagonal vs non-diagonal movement). But your algorithm needs to take into account the previous step to figure it out.. is it for sure possible to adapt A* this way - if that is the case why the original algorithm doesn't do this already?
Comment: Also you have to prove that your heuristic is admissible (http://en.wikipedia.org/wiki/A*_search_algorithm#Admissibility_and_optimality) and is not overestimating the cost to the goal because that could lead you to suboptimal paths since the algorithm will start considering less candidate nodes from what I understand
Comment: @MichailMichailidis In regards to optimality, I am claiming that your algorithm does not always return a minimal path with the least number of turns. For example, in case 3 of your post, you can find a minimal path with only two turn.
Comment: Well I am just getting basic A* that actually hugs the obstacles. Mine just simplifies/straightens the path. It doesn't make it have optional number of turns if A*'s one was not optimal turn-wise either. I am curious about the implementation :) when you have time. Also I wonder what is the complexity for the modified grid you are talking about. I assume that A* will run only once right?
Answer: I have come up with somewhat of a fix that is a simple addition to your original code, but it doesn't work in all situations (see image below) because we are limited to what the A* returns us. You can see my jsfiddle here
I added the following code to your simplifyPath function right before the return. What it does is strips out extra steps by seeing if there is a clear path between non-adjacent steps (looking at larger gaps first). It could be optimized, but you should get the gist from what I've got.
do{
    shortened = false;
    loop:
    for(i = 0; i < simplePath.length; i++) {
        for(j = (simplePath.length - 1); j > (i + 1); j--) {
            if(this.isPathClear(simplePath[i],simplePath[j])) {
                simplePath.splice((i + 1),(j - i - 1));
                shortened = true;
                break loop;
            }
        }
    }
} while(shortened == true);

You can see below that this removes the path that goes in on the left (as in the question) but also that not all the odd turns are removed. This solution only uses the points provided from the A*, not points in between on the path - for example, because the 2nd point does not have a straight unobstructed line to the 4th or 5th points, it cannot optimize point 3 out. It happens a lot less than the original code, but it still does give weird results sometimes.
Answer: In edition to nodes having references to their parent nodes. Also store which direction that node came from inside a variable. In my case there was only two possibilities horizontally or vertically. So I created two public static constants for each possibility. And a helper function named "toDirection" which takes two nodes and return which direction should be taken in order to go from one to another:
public class Node {
    final static int HORIZONTALLY = 0;
    final static int VERTICALLY = 1;

    int col, row;
    boolean isTravelable;
    int fromDirection;
    double hCost;
    double gCost;
    double fCost;

    Node parent;

    public Node(int col, int row, boolean isTravelable) {
        this.col = col;
        this.row = row;
        this.isTravelable = isTravelable;
    }

    public static int toDirection(Node from, Node to) {
        return (from.col != to.col) ? Node.HORIZONTALLY : Node.VERTICALLY;
    }
}

Then you can change your weight calculation function to take turns into account. You can now give a small punishment for turns like:
public double calcGCost(Node current, Node neighbor) {
    if(current.fromDirection == Node.toDirection(current, neighbor)) {
        return 1;
    } else{
        return 1.2;
    }
}

Full code: https://github.com/tezsezen/AStarAlgorithm
Answer: At the risk of potential down voting, I will try my best to suggest an answer. If you weren't using a third party plugin I would suggest a simple pop/push stack object be built however since you are using someone else's plugin it might be best to try and work along side it rather than against it.
That being said I might just do something simple like track my output results and try to logically determine the correct answer. I would make a simple entity type object literal for storage within an array of all possible path's? So the entire object's life span is only to hold position information. Then you could later parse that array of objects looking for the smallest turn count.
Also, since this third party plugin will do most of the work behind the scenes and doesn't seem very accessible to extract, you might need to feed it criteria on your own. For example if its adding more turns then you want, i.e. inside the door looking square, then maybe sending it the coordinates of the start and end arent enouugh. Perhaps its better to stop at each turn and send in the new coordinates to see if a straight line is now possible. If you did this then each turn would have a change to look and see if there is an obstruction stopping a straight line movement.
I feel like this answer is too simple so it must be incorrect but I will try nonetheless...
//Entity Type Object Literal
var pathsFound = function() {

    //Path Stats
    straightLine: false,
    turnCount: 0,
    xPos: -1, //Probably should not be instantiated -1 but for now it's fine
    yPos: -1,

    //Getters
    isStraightLine: function() { return this.straightLine; },
    getTurnCount: function() { return this.turnCount; },
    getXPos: function() { return this.xPos; },
    getYPos: function() { return this.yPos; },

    //Setters
    setStraightLine: function() { this.straightLine = true; },
    setCrookedLine: function() { this.straightLine = false; },
    setXPos: function(val) { this.xPos = val; },
    setYPos: function(val) { this.yPos = val; },

    //Class Functionality
    incrementTurnCounter: function() { this.turnCount++; },
    updateFullPosition: function(xVal, yVal) {
        this.xPos = xVal;
        this.yPos = yVal.
    },
}

This way you could report all the data every step of the way and before you draw to the screen you could iterate through your array of these object literals and find the correct path by the lowest turnCount.
Comment: Your answer is just a data model - it doesn't have an algorithm/heuristic. On top of that I don't think that A* can return all shortest paths... He will have to probably use an adaptation of Dijkstra's or Johnson's algorithm to return all shortest paths between source and destination and then run something like yours.
Answer:

var img,
    field = document.getElementById('field'),
    EngineBuilder = function(field, size) {
        var context = field.getContext("2d"),
            graphSettings = { size: size, mid: Math.ceil(size/2)},
            engine = {
                getPosition: function(event) {
                    var bounds = field.getBoundingClientRect(),
                        x = Math.floor(((event.clientX - bounds.left)/field.clientWidth)*field.width),
                        y = Math.floor(((event.clientY - bounds.top)/field.clientHeight)*field.height),
                        node = graph.grid[Math.floor(y/graphSettings.size)][Math.floor(x/graphSettings.size)];

                    return {
                        x: x,
                        y: y,
                        node: node
                    }
                },
                drawObstructions: function() {
                    context.clearRect (0, 0, 320, 200);
                    if(img) {
                        context.drawImage(img, 0, 0);
                    } else {
                        context.fillStyle = 'rgb(0, 0, 0)';
                        context.fillRect(200, 100, 50, 50);
                        context.fillRect(0, 100, 50, 50);
                        context.fillRect(100, 100, 50, 50);
                        context.fillRect(0, 50, 150, 50);
                    }
                },
                simplifyPath: function(start, complexPath, end) {
                    var previous = complexPath[1], simplePath = [start, {x:(previous.y*graphSettings.size)+graphSettings.mid, y:(previous.x*graphSettings.size)+graphSettings.mid}], i, classification, previousClassification;
                    for(i = 1; i < (complexPath.length - 1); i++) {
                        classification = (complexPath[i].x-previous.x).toString()+':'+(complexPath[i].y-previous.y).toString();

                        if(classification !== previousClassification) {
                            simplePath.push({x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid});
                        } else {
                            simplePath[simplePath.length-1]={x:(complexPath[i].y*graphSettings.size)+graphSettings.mid, y:(complexPath[i].x*graphSettings.size)+graphSettings.mid};
                        }
                        previous = complexPath[i];
                        previousClassification = classification;
                    }
                    simplePath.push(end);
                    return simplePath;
                },
                drawPath: function(start, end) {
                    var path, step, next;
                    if(this.isPathClear(start, end)) {
                       this.drawLine(start, end);
                    } else {
                        path = this.simplifyPath(start, astar.search(graph, start.node, end.node), end);
                        if(path.length > 1) {
                            step = path[0];
                            for(next = 1; next < path.length; next++) {
                                this.drawLine(step, path[next]);
                                step = path[next];
                            }
                        }
                    }
                },
                drawLine: function(start, end) {
                    var x = start.x,
                        y = start.y,
                        dx = Math.abs(end.x - start.x),
                        sx = start.x<end.x ? 1 : -1,
                        dy = -1 * Math.abs(end.y - start.y),
                        sy = start.y<end.y ? 1 : -1,
                        err = dx+dy,
                        e2, pixel;

                    for(;;) {
                        pixel = context.getImageData(x, y, 1, 1).data[3];
                        if(pixel === 255) {
                            context.fillStyle = 'rgb(255, 0, 0)';
                        } else {
                            context.fillStyle = 'rgb(0, 255, 0)';
                        }
                        context.fillRect(x, y, 1, 1);

                        if(x === end.x && y === end.y) {
                            break;
                        } else {
                            e2 = 2 * err;
                            if(e2 >= dy) {
                                err += dy;
                                x += sx;
                            }
                            if(e2 <= dx) {
                                err += dx;
                                y += sy;
                            }
                        }
                    }
                },
                isPathClear: function(start, end) {
                    var x = start.x,
                        y = start.y,
                        dx = Math.abs(end.x - start.x),
                        sx = start.x<end.x ? 1 : -1,
                        dy = -1 * Math.abs(end.y - start.y),
                        sy = start.y<end.y ? 1 : -1,
                        err = dx+dy,
                        e2, pixel;

                    for(;;) {
                        pixel = context.getImageData(x, y, 1, 1).data[3];
                        if(pixel === 255) {
                            return false;
                        }

                        if(x === end.x && y === end.y) {
                            return true;
                        } else {
                            e2 = 2 * err;
                            if(e2 >= dy) {
                                err += dy;
                                x += sx;
                            }
                            if(e2 <= dx) {
                                err += dx;
                                y += sy;
                            }
                        }
                    }
                }
            }, graph;
            engine.drawObstructions();
            graph = (function() {
                var x, y, rows = [], cols, js = '[';
                for(y = 0; y < 200; y += graphSettings.size) {
                    cols = [];

                    for(x = 0; x < 320; x += graphSettings.size) {
                        cols.push(context.getImageData(x+graphSettings.mid, y+graphSettings.mid, 1, 1).data[3] === 255 ? 0 : 1);
                    }
                    js += '['+cols+'],\n';
                    rows.push(cols);
                }
                js = js.substring(0, js.length - 2);
                js += ']';
                document.getElementById('Graph').value=js;
                return new Graph(rows, { diagonal: true });
            })();
            return engine;
        }, start, end, engine = EngineBuilder(field, 10);

field.addEventListener('click', function(event) {
    var position = engine.getPosition(event);
    if(!start) {
        start = position;
    } else {
        end = position;
    }
    if(start && end) {
        engine.drawObstructions();
        engine.drawPath(start, end);
        start = end;
    }
}, false);
#field {
border: thin black solid;
    width: 98%;
    background: #FFFFC7;
}
#Graph {
    width: 98%;
    height: 300px;
    overflow-y: scroll;
}

Click on any 2 points on white spaces and a path will be drawn
<canvas id='field' height

='200' width='320'></canvas>
<textarea id='Graph' wrap='off'></textarea>
Comment: The code sent still has the issue of unneeded turns


Matrix Norm Definition

Question: I don't understand the intuition behind the definition of a matrix norm: $\displaystyle \|A\|_p = \max_{x\neq0}\frac{\|Ax\|_p}{\|x\|}$.
Why is the arbitrary vector $\vec{x}$ included in the expression? Intuitively, what does this mean?
Answer: One way to think of the matrix norm is a way of measuring the deformation of the unit sphere under transformation by $A$ - another way to write $\|A\|_p$ is $$\max_{\|x\| = 1} \|Ax\|_p.$$ It is measuring the largest $p$ norm of $Ax$ among all unit vectors $x$.
Answer: To say that the norm is $N$ means the mapping cannot take any vector to a vector that's more than $N$ times as big, although it can take some vectors to a vector that is exactly $N$ times as big.

Matrix Norm Definition


Error in code. Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Question: I'm trying to run this query but no matter what I do I keep getting this error and I cannot work it out. Any help would be appreciated.
select
  CC.ContactID,

from
  Client C
  join Contacts CC on CC.ContactID = C.ContactID
 where

        ClientID In (

                                  Select
                                    ClientID,Sum(Total-allocated) as Bal
                                  from
                                    Main
                                  Where
                                    Total <> Allocated
                                    and NomTypeID < 10
                                  Group By
                                    ClientID
                                  HAVING Sum(Total-allocated) > 10
                             )

Comment: Please tag the database you are using
Answer: I'm not sure what DB kind you are using (so I also could not test my answer).
But in general when you use IN you need the subquery to return only one column.
So the query should be (removed the Sum(Total-allocated) as Bal):
select
  CC.ContactID,

from
  Client C
  join Contacts CC on CC.ContactID = C.ContactID
 where

        ClientID In (

                                  Select
                                    ClientID
                                  from
                                    Main
                                  Where
                                    Total <> Allocated
                                    and NomTypeID < 10
                                  Group By
                                    ClientID
                                  HAVING Sum(Total-allocated) > 10
                             )

Answer: Please use below query,
select
  CC.ContactID from
Client C
join Contacts CC on CC.ContactID = C.ContactID
join (Select ClientID,Sum(Total-allocated) as Bal from Main Where
Total <> Allocated and NomTypeID < 10
Group By ClientID HAVING Sum(Total-allocated) > 10)) m
on (C.ClientID = m.ClientID);


How do I run stats on a data set organized by bins?

Question: I have a problem I am working on and I have data set up in the following way:
I wanted to test in flowers change their bloom size given the time of day, so I sampled random flowers in the morning and in the evening, measuring the diameter of their bloom.  These measurements were separated into size bins, like <3cm, 4-6cm, 7-9cm, etc.
I am not sure how to run this data since each flower was not sampled at morning and evening, it was a different flower each time....Any help would be greatly appreciated!
Comment: Are they the same species and same geographic area?
Comment: Yes they are the same species and in the same area.
Answer: Because you have a random sample of the same species from the same area, it looks like you can make a valid conclusion about the behavior of this flower in morning and evening. Since they are all organized in bins, you can make histograms to see if there is a visual difference in means, percentiles, or what kind of distribution they best fit. Then, find a statistical test that helps you test a hypothesis.
Answer: Looks like you could use ordinal logistic regression with the dependent variable being size and the independent variable being time of day.


render($page['content']) in the wrong place!

Question: Ok I'm having this really weird problem with my Drupal 7 site. I have edited my page.tpl.php file. Following is the html where this oddity occurs

<?php echo $title; ?>

            <?php print render($page['content']); ?>

Bestselling

                           <?php print render($page['right']['views_bestsellers-block']); ?>

Poll

                       <?php print render($page['right']['poll_blocks_11']); ?>

So far everything looks fine. But when opened in the browser print render($page['content']); prints outside the table before it! I have checked this through firebug.
I have also edited a node.tpl.php file and everything is fine inside it.
Can anyone suggest what is going on?
Comment: In what way do I override the `CSS`?
Comment: `tables` and `div` elements have different styles. that might be the problem.. better you use `div` elements.
Comment: But using `table` is my requirement. Without it I can't seem to get my 'bestselling' and 'poll' blocks on the left. This is just weird, why wouldn't Drupal allow this?
Comment: why dont you override `CSS` on/with `table` and `div`
Comment: Two ways: `Inline styling`, where you need to write the css in inline the element tags.

`Javascript` when page loads, change the css you want to display..

Its better to use `inline styling`, cos it renders before the page loads. and javascript will change the styling after page load..
Comment: And if this is so, how come the other two blocks print inside the `table` while only this one doesn't?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3501/discussion-between-rafee-and-ali)
Comment: Thanks but I solved the problem. Turns out, the content in my `node.tpl.php` was wrapped in a `tr` tag. Don't know how it got there. When I removed it everything was fine. Thanks very much for your help anyway.. ^-^
Answer: The content in my node.tpl.php was wrapped in a tr tag. Don't know how it got there. When I removed it everything was fine.


How to prove that every infinite cardinal $Z$ is equal the countable sum of sets of size $Z$?

Question:
Any infinite cardinal $Z$ can be expressed as a countable union of disjoint sets, each of them has the same size $Z$.

Any help will be appreciated.
Comment: You ask about any infinite cardinal $Z$, but the answer (which you seem happy with) assumes $Z$ is the set of integers.  Which is it?  The statement is true for any infinite cardinal $Z$
Comment: Dear Ziko: if you find an answer to be helpful, you are encouraged to accept it (you can accept exactly one answer per question). To accept an answer, you can simply click on the $\checkmark$ to the left of the answer you'd like to accept. You also get two reputation points for each answer you accept. Soon, with just a little more reputation, you'll also be able to "up-vote" as many answers as you'd like!
Answer: Hint: Recall that $Z$ and $Z \times \mathbb{N}$ have the same cardinality.  It should be much easier to work with the second set.
Comment: @ArthurFicher .... I need an explicit proof. If possible
Comment: @ZikoSarbi: Can you think of how to express $Z \times \mathbb{N}$ as the disjoint union of countably many sets each having the same cardinality as $Z$?
Comment: @ArthurFicher I am really sorry to tell you that I can not express it. Could you please give me a proof in general not only for $\mathbb{N}\times \mathbb{Z}$
Comment: @ZikoSarbi: This is how one would prove the general case: reduce it to a case that is much easier!  (Note that I am using $Z$, as you did in your question, and not $\mathbb Z$, the set of integers.)  There are two things that are left to do.  The first is the content of my first comment.  The second is to demonstrate that knowing that one can partition $Z \times \mathbb{N}$ into countable many pairwise disjoint sets each having the same cardinality as $Z$, then the same can be done to $Z$.  (This will use the fact that $Z$ and $Z \times \mathbb N$ have the same cardinality.)
Comment: @ArthurFicher you mean each set is of this form $\mathbb{Z}\times \{n\}$
Comment: @ZikoSarbi: Yes!!
Comment: @ArthurFicher Thanks dear for this tip , excellent
Comment: @ZikoSarbi: You're welcome! My original answer was perhaps a bit obscure, but I'm glad you got it.