css apresenta erro no chorme

Question: Nessa pagina, http://www.magicforbaby.com.br/contato.php?form, os campos do formulário estão estilizados corretamente.
Localmente com os inputs texts está tudo como deve estar, mas na web está fora e os css estão corretamente postados.
Porque será? Detalhe: apenas no Firefox esse erro não ocorreu!

contato.php
<?php require_once "config.php" ; ?>
<!doctype html>

    <title><?php echo $constantes->getTituloSite(); ?></title>
    <?php  require_once("_global/_meta/meta.ini"); ?>
    <link rel="shortcut icon" type="image/x-icon" href="_img/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="_global/_css/estilo.css">
    <link rel="stylesheet" type="text/css" href="_global/_css/site.css">
    <link rel="stylesheet" type="text/css" href="_global/_css/menu.css">
    <link rel="stylesheet" type="text/css" href="_global/_css/jHtmlArea.css" />

<?php require_once "_required/menu.php"; ?>

<?php require_once "contatoConteudo.php"; ?>

<?php require_once "_required/base.php"; ?>

<?php require_once "_required/final.php"; ?>

contatoConteudo.php
<?php if(isset($_GET["form"]) ) {   ?>

Fale Conosco

  <form class="formularios" style="width: 450px; text-align:center" id="contato" action="?" method="post">

      Assunto<select style="width: 212px; height:52px;" id="assunto" name="assunto" required>
        <option value="">Escolha o assunto</option>
        <option value="1">Quero Comprar</option>
        <option value="2">Quero Vender</option>
        <option value="3">Indicação</option>
        <option value="4">Elogio</option>
        <option value="5">Pedido de Catálogo</option>
        <option value="6">Outro</option>
      </select>

          Qual?<input type="text" class="typeTextMedio" maxlength="200" id="qual" name="qual" />

      Nome<input type="text" class="typeTextMedio" maxlength="200" id="nome" name="nome" required />

        Telefone<input type="tel" class="typeTextMedio" maxlength="14" id="telefone" name="telefone" />

      Email<input type="email" class="typeTextMedio" required maxlength="200" id="email" name="email" />

Descrição

      <textarea class="textarea" name="descricao" id="descricao" cols="60" rows="15"></textarea>

      <input name="envia" class="btnAcesso" type="submit" value="Enviar" />

  </form>

<?php } ?>

<?php

  if(isset($_POST["envia"]) )  {

    $assunto = $phpUtil->contatoTipos($_POST["assunto"]);

    require_once "_controlls/_models/Emails.php";
    require_once "_controlls/_daos/EmailsDao.php";
    $emailsDao = new EmailsDao($conexao);

    $email = new Emails(
                     date("Y-m-d"),
                     "n",
                     $_POST["nome"],
                     $_POST["email"],
                     preg_replace( '#[^0-9]#', '', $_POST["telefone"] ),
                     "",
                     $_POST["assunto"],
                     $_POST["descricao"]);

    $emailsDao->cadastrar($email);

    $texto  = "
Email enviado pelo site da ".$constantes->getTituloSite()."

";
    $texto .= "Nome: ".$_POST["nome"]."

";
    $texto .= "Telefone: ".$_POST["telefone"]."

";
    $texto .= "E-mail: ".$_POST["email"]."

";
    $texto .= "Intersse: ".$assunto."

";
    $texto .= "Descrição:
".nl2br($_POST["descricao"])."
";

    require_once "_controlls/_models/EmailEnviar.php";
    require_once "_controlls/_daos/EmailEnviarDao.php";

    $emailEnviar = new EmailEnviar(
          $constantes->getTituloSite(),
          $constantes->getEmailSite(),
          $_POST["nome"],
          $_POST["email"],
          "Re: ".$assunto,
          $texto
    );

    $emailEnviarDao = new EmailEnviarDao();

    $enviarEmail = $emailEnviarDao->enviaEmail($emailEnviar);

    if ($enviarEmail["success"] == 0) {

        echo $phpUtil->sucesso ("Mensagem enviada com sucesso!");

    }
    else {

        echo $phpUtil->erro ($enviarEmail["errors"]);

    }

  }

?>

estilo.css
@charset "utf-8";
/* CSS Document */

@import url('http://fonts.googleapis.com/css?family=Open+Sans');
* {
    font-family: 'Open Sans';
    margin: 0;
    padding: 0;
}
body {
    font-size: 12px;
}
.carregando {
    background: #ffffff;
    font-size: 10px;
    font-family: verdana;
    position: absolute;
    width: 100%;
    height: 600px;
    text-align: center;
    z-index: 10000;
}
.carregando img {
    position: relative;
    vertical-align: middle;
    padding: 10px;
    z-index: 10001;
}
.meio {
    display: none;
}
.sessoes {
    width: 1000px;
    margin: 0 auto;
}
.formularios {
    margin: 0 auto;
}
img {
    border: 0;
    max-width: 100%;
}
ul {
    list-style: none;
}
a, a:hover {
    text-decoration: none;
}
input[type=checkbox] {
    background-color: #CCCCCC;
    width: 40px;
    height: 40px;
}
input[type=button], input[type=submit], input[type=reset] {
    background-color: #CCCCCC;
    color: #000;
    font-weight: bold;
}
.typeTextGrande, .typeTextMedio, .typeTextPequeno {
    height: 36px;
    padding: 4px;
}
.typeTextPequeno {
    width: 100px;
}
.typeTextMedio {
    width: 200px;
}
.typeTextGrande {
    width: 550px;
}
label {
    height: 40px;
    line-height: 40px;
    display: inline-block;
    vertical-align: middle;
}
.labelPequeno {
    width: 100px;
}
.labelMedio {
    width: 200px;
}
.labelGrande {
    width: 300px;
}
.h1Centralizado, .h1CentralizadoAvisos {
    width: 100%;
    margin-top: 50px;
    line-height: 50px;
    text-align: center;
}
.textoPrincipal, .sucesso, .erro {
    width: 100%;
    height: 300px;
    line-height: 300px;
    text-align: center;
}
.erro, .h1CentralizadoAvisos {
    color: #F00;
}
.clearBoth {
    clear: both;
}
.btnAcesso, .btnPesquisa {
    background-size: contain;
    background-repeat: no-repeat;
    background-position: right;
    width: 208px;
    height: 44px;
}
.btnAcesso {
    background-image: url(../../_img/acesso.png);
}
.btnPesquisa {
    background-image: url(../../_img/pesquisar.png);
}
/*///////////////////////// INICIO LISTAGENS ///////////////*/
.lista {
    margin: 0 auto;
}
select {
    width: 110px;
    height: 50px;
}
ul.listaTopo, ul.listaRegistros {
    margin: 0 auto;
    padding: 0;
    width: 100%;
}
ul.listaTopo {
    background-color: #000;
    color: #FFF;
}
ul.listaTopo li, ul.listaRegistros li {
    display: inline-block;
    height: 50px;
    line-height: 50px;
    vertical-align: middle;
    text-align: center;
    font-weight: bold;
}

/*///////////////////////// FIM LISTAGENS /////////////////*/

@media screen and (min-width: 0px) and (max-width:860px) {
.sessoes {
    width: 100%;
}
.sucesso, .erro, .h1Centralizado, {
 line-height:100px;
}
}

site.css
@charset "utf-8";
/* CSS Document */

.topo, .menu, .conteudo, .cont, .base, .final {
    clear: both;
    position: relative;
    width: 100%;
}
.logo, .menu {
    display: inline-block;
    vertical-align: top;
    height: 150px;
}
.logo {
    width: 10%;
}
.menu {
    width: 89%;
}
.banner {
    display: inline-block;
    height: 657px;
}
.listaCategorias {
    margin: 0 auto;
    width: 100%;
    text-align: center;
}
.listaCategorias li {
    display: inline-block;
    vertical-align: top;
    height: 350px;
}
.sobre {
    margin:0 auto;
    width: 80%;
}
.base {
    background-color: #FCB412;
    border-top: 5px #FC0000 solid;
    border-bottom: 5px #FC0000 solid;
    font-size: 12px;
}
.baseEsquerda {
    display: inline-block;
    vertical-align: top;
    width: 45%;
    padding: 3% auto;
    padding: 5px;
}
.barraBase {
    display: inline-block;
    vertical-align: top;
}
.barraBase .hr {
    display: block;
    width: 6px;
    height: 180px;
    background-color: #FC0000;
    border: none;
}
.baseDireita {
    display: inline-block;
    vertical-align: top;
    width: 45%;
    padding: 3% auto;
}
.final {
    background-color: #000;
    color: #FFF;
}
.finalEsquerda, .finalDireita {
    display: inline-block;
    vertical-align: middle;
}
.finalEsquerda {
    text-align: left;
    width: 700px;
}
.finalDireita {
    text-align: right;
    width: 290px;
}

@media screen and (min-width: 0px) and (max-width:860px) {

.listaCategorias li {
    border: #000 .1px solid;
}

.final, .base, .baseEsquerda, .baseDireita, .finalEsquerda, .finalDireita {
    width: 95%;
    font-size: 10px;
    text-align: center;
}
.barraBase {
    display: none;
}
.final {
    height: 100px;
}
}

menu.css
@charset "utf-8";
/* CSS Document */

.menuPrincipal {
}

.menuPrincipal li {
  display:inline;
}

.menuPrincipal li a {
  display:inline-block;
  vertical-align:middle;
  width:19.6%;
  height:50px;
  line-height:50px;
  text-align:center;
  font-size: 24px;
  color: rgb(223,189,92);
}

.menuPrincipal li a:hover {
  color: #FFF;
  background-color:rgb(223,189,92);
}

.menuBase li a {
    color:#000;
}

.menuBase li a:hover {
    color:#FFF;
}

@media screen and (min-width: 0px) and (max-width:860px) {

.menuAbrir {
    position: absolute;
    top: 0;
    right: 0;
    width: 60px;
    height: 60px;
}
.menuNav {
    position: absolute;
    top: 0;
    width:100%;
    height: 100%;
    display: none;
    position: fixed;
    z-index: 1500;
    background-color:#005E9C;
}

.menuFechar {
    right: 0;
    position: absolute !important;
}

ul.menuPrincipal li a {
    width: 100%;
}

}

@media screen and (min-width: 1000px) {
.menuAbrir, .menuFechar {
    display: none;
}

ul.menuPrincipal li {
    display: inline;
}
ul.menuPrincipal li a {
    width: 195px;
}
}

jhtmlarea.css
div.jHtmlArea { display: block; overflow: hidden; border: solid 1px #aaa; background-color: #fff; }

div.jHtmlArea iframe, div.jHtmlArea textarea { border: none;   }

div.jHtmlArea div { display: inline-block; padding: 0px; margin: 0px; }
div.jHtmlArea .ToolBar { display: inline-block; background: #fbfbfb; border-bottom: solid 1px #aaa; }
div.jHtmlArea .ToolBar ul { border: solid 1px #ccc; margin: 1px; padding: 1px; float: left; background: #fff url(jHtmlArea_Toolbar_Group_BG.png) repeat-x;}
div.jHtmlArea .ToolBar ul li { list-style-type: none; float: left; border: none; padding: 1px; margin: 1px; }
div.jHtmlArea .ToolBar ul li:hover { border: solid 1px #ccc; background: #ddd url(jHtmlArea_Toolbar_Group__Btn_Select_BG.png); padding: 0; }
div.jHtmlArea .ToolBar ul li a { display: block; width: 16px; height: 16px; background: url(jHtmlArea.png) no-repeat -16px -500px; border: none; cursor: pointer; padding: 0px; }
div.jHtmlArea .ToolBar ul li a.highlighted { border: solid 1px #aaa; background-color: #bbb; padding: 0; }
div.jHtmlArea .ToolBar ul li.separator {height: 16px; margin: 0 2px 0 3px; border-left: 1px solid #ccc;}
div.jHtmlArea .ToolBar ul li.separator:hover { padding: 1px; background-color: #fff; border-top:none; border-bottom:none; border-right:none;}

div.jHtmlArea .ToolBar ul li a:hover { }
div.jHtmlArea .ToolBar ul li a.bold { background-position: 0 0; }
div.jHtmlArea .ToolBar ul li a.italic { background-position: -16px 0; }
div.jHtmlArea .ToolBar ul li a.underline { background-position: -32px 0; }
div.jHtmlArea .ToolBar ul li a.strikethrough { background-position: -48px 0; }
div.jHtmlArea .ToolBar ul li a.link { background-position: -64px 0; }
div.jHtmlArea .ToolBar ul li a.unlink { background-position: -80px 0; }
div.jHtmlArea .ToolBar ul li a.orderedlist { background-position: -96px 0; }
div.jHtmlArea .ToolBar ul li a.unorderedlist { background-position: -112px 0; }
div.jHtmlArea .ToolBar ul li a.image { background-position: -128px 0; }
div.jHtmlArea .ToolBar ul li a.cut { background-position: -144px 0; }
div.jHtmlArea .ToolBar ul li a.copy { background-position: -160px 0; }
div.jHtmlArea .ToolBar ul li a.paste { background-position: -176px 0; }

div.jHtmlArea .ToolBar ul li a.html { background-position: -192px 0; opacity:0.6; filter:alpha(opacity=60);}
div.jHtmlArea .ToolBar ul li a.html.highlighted { opacity:1.0; filter:alpha(opacity=100);}

div.jHtmlArea .ToolBar ul li a.h1 { background-position: 0 -16px;}
div.jHtmlArea .ToolBar ul li a.h2 { background-position: -16px -16px;}
div.jHtmlArea .ToolBar ul li a.h3 { background-position: -32px -16px;}
div.jHtmlArea .ToolBar ul li a.h4 { background-position: -48px -16px;}
div.jHtmlArea .ToolBar ul li a.h5 { background-position: -64px -16px;}
div.jHtmlArea .ToolBar ul li a.h6 { background-position: -80px -16px;}
div.jHtmlArea .ToolBar ul li a.subscript   { background-position: -96px -16px;}
div.jHtmlArea .ToolBar ul li a.superscript { background-position: -112px -16px;}
div.jHtmlArea .ToolBar ul li a.indent { background-position: -128px -16px;}
div.jHtmlArea .ToolBar ul li a.outdent { background-position: -144px -16px;}
div.jHtmlArea .ToolBar ul li a.horizontalrule { background-position: -160px -16px;}
div.jHtmlArea .ToolBar ul li a.p { background-position: -176px -16px;}

div.jHtmlArea .ToolBar ul li a.justifyleft { background-position: 0 -32px;}
div.jHtmlArea .ToolBar ul li a.justifycenter { background-position: -16px -32px;}
div.jHtmlArea .ToolBar ul li a.justifyright { background-position: -32px -32px;}
div.jHtmlArea .ToolBar ul li a.increasefontsize { background-position: -48px -32px;}
div.jHtmlArea .ToolBar ul li a.decreasefontsize { background-position: -64px -32px;}
div.jHtmlArea .ToolBar ul li a.forecolor { background-position: -80px -32px;}

Comment: Estás a usar algum reset?
Comment: só de margin e padding 0 no *{}
Comment: note que no select não ocorre esse rro
Comment: Coloca o css na pergunta e o html, acho que algo com isset....
Comment: outro detalhe que acabo de observar é que na web, você pode notar, que a pagina está começando um pouco para baixo e para o pessoal do php, esta página é utf-8 sem bom.
Comment: Colocar o código ajuda
Comment: ok, html já foi e o css é grande. Põe ele todo?
Comment: hehe na verdade coloquei errado num é isset é inset
Comment: passou perto, hehehe. Mas não usei inset não. Só no firerfox funciona direito!
Comment: Mano é tanto nome, tinha que ser tudo em português..kkkk
Comment: Mas, sério: notou que há uma diferença na figura nas duas mostras? Que na web, parece que tem alguma coisa tipo que empurrando a página para baixo? Já me certifiquei: não é o BOM do UTF-8.
Comment: O css que tem é esse dentro das tags ou tem outro?
Comment: Você que igual a qual o chrome ou firefox?
Comment: pois é, posso até colocar tudo aqui mas vai ficar enorme. Você não acha melhor acessar a página e ver o código fonte? Mas se achar melhor, posto todo oi código.
Comment: Só o chorme não apresenta o erro. Pronto: coloquei tudo lá!
Comment: A pergunta é se quer igual ao que o chrome apresenta ou o firefox? o input?
Comment: quero igual ao que o firefox apresenta!. Pois só o chorme está diferente. Mas, localmente (localhost), todos os browsers, inclusive o chrome, funcionam corretamente. Por isso postei a figura na pergunta!
Answer: O problema ocorre por você não estar "resetando" corretamente o css e cada navegador estar usando um valor padrão diferente.
No caso para ser mais específico o problema está no box-sizing, onde no chrome está por padrão como border-box e no Firefox está como content-box, o que altera o calculo do tamanho do elemento.
No caso se você alterar o seu css adicionando um valor padrão para o content-box faz com que fique igual no Chrome e Firefox, não testei em outro navegador
* {
    font-family: 'Open Sans';
    margin: 0;
    padding: 0;
    box-sizing: content-box;
}

Mas eu recomendaria você a procurar um reset mais completo, pois podem acontecer outros casos de diferenças entre os navegadores
Comment: entendi. Mas me tira uma dúvida. Porque isso só ocorrer na internet. No localhost não está ocorrendo. Veja na imagem. Se o navegador é o mesmo, o comportamento não deveria ser o mesmo? Note que no lado direito a página está sendo empurrada para baixo em relação à página do lado esquerdo!
Comment: É dificil dizer, mas eu diria que ou existe alguma diferença no que está sendo retornado pelo seu servidor de desenvolvimento que faz o Chrome tratar a página de forma diferente ou ele está a tratando de forma diferente simplesmente por estar no localhost
Comment: o problema é que o código fornte (ctrl+u) de ambos é o mesmo!
Comment: Uma coisa que você pode tentar é abrir o Console no Chrome e rodar o comando `document.compatMode` exatamente desta forma, ele vai te retornar o modo de renderização do documento, se estiverem diferentes no seu local e no remoto esse pode ser o problema. E pelo que vi aqui o Chrome me retornou que está no modo `BackCompat` que também é conhecido como `Quirks Mode`, enquanto que o Firefox está retornando `CSS1Compat`, que seria o modo que segue, ou pelo menos tenta, seguir o padrão que todo navegador deveria seguir
Comment: deu certo. Agora vou ler com calma para estudar isso direitinho! Obrigado!
Answer: Adiciona isso vê se dá certo.

input {
    background-color: #CCCCCC;
    color: #000;
    font-weight: bold;
    -webkit-box-shadow:0 0 5px #666 inset;
    -moz-box-shadow:0 0 5px #666 inset;
    box-shadow:0 0 5px #666 inset;
}

css apresenta erro no chorme


Are samples dependent or independent, paired or unpaired?

Question: An animal performs a task in a T-maze. Sometimes he chooses the right part of the maze (right trials) and sometimes left(left trials).
I want to know if there are differences in firing rate of one neuron between these two types of trials: left and right. So, my independent variable is left vs right trials.
For example, I have 7 values of firing rate corresponding to 7 left trials and 10 values of firing rate corresponding to 10 right trials.
Since all firing rates correspond to the same neuron I thought samples were dependent and paired. By reading on Internet, I thought I may be wrong. Can anyone help me?
And, what stats would you use to check differences between left and right trials?
Thanks,
Ana
Comment: One way to view your experiment is that it consists of a sequence of 17 trials.  In each trial two values are observed: firing rate and direction of turn.  Since these trials are all for the same animal, you can justify making inferences about that animal, but it would be difficult (on a statistical basis alone) to generalize from that animal to any larger population. It is a matter for the data to determine whether this sequence of observations can be considered independent or not: plausibly, there could be some "carry over" effect from one state of the neuron to the next.
Comment: Please add that information as an edit to the original question, many people do not read comments. And, what you explain seems to tell me that *left* and *right* here is part of the result, and not really different kinds of trials? Your post could benefit from an extended explication!
Comment: Can you explain what is *left and right trials*?
Comment: Left and right trials correspond to the independent variable: animals perform a task on a maze and in some trials they choose right and in other trials they choose left.
Answer: Your data cannot be paired, as your animal can choose each time at random which side it uses and therefore you might end up with different numbers of observations per individual for left and right side trials. In the most extreme case, an animal chooses only right trials and you will only observe right side data.
For this, you will require some form of mixed effects model structure, where the individual from which you observe the trials is a model layer.
Unless you assume a learning behaviour of the test animal, the trials are independent. If you have such a learning behaviour, then your trials are dependent and you will require an additional variable counting that this is the i-th trial on the left or j-th trial on the right side and trial (i+1) on the left and (j+1) on the right side will have dependence on the the trials before.
Comment: Then your trials are independent.
Comment: Unless the outcome of one trial affects the choice or outcome of the following trial (= as long as the animals chooses left vs. right at random), they are independent. If it starts developing 'preferences' and starts out with 6 left trials, afterwards choosing only right trials because it gets better rewards or less demanding tasks, the independence is not valid.
Comment: There is not learning. The animals learn the task before I collect the data. If they couldn't choose between left and right, would the data be paired?
Comment: After reading your answers, I understand that trials are independent for both cases: chosen and not chosen trials. Am I right?
Comment: Data is not normal. I checked normality of data with Shapiro test, histograms shapes and q-q plots. Could I use a Mann-Withney U-test or a Wilcoxon rank-sum test to check differences between left and right trials?
Comment: I would not use a non-parametric rank beased test for such small sample sizes, as you described them. In my experience, the power of the test is typically too small for detecting anything, unless the effects are large enough to already be detectable with a simple graphical exploration.
Comment: When I use the Wilcoxon rank-sum on Python, I find many p values<0.05 in many neurons so it seems it detects well significant differences. Do you think is the right test to be used?
Comment: If you do this for a lot of neurons, you will have to correct for multiple testing!
Comment: If I apply the Wilcoxon rank-sum test for every neuron, so I get a p value for every neuron. Do I need to correct for multiple testing? What's the procedure to do it?


Problema ao eliminar da memória um TObjectList

Question: estou com um problema para limpar da memoria um TObjectList< TLabel>,
em especifico o ObjectList do tipo TLabel.
Eu criei duas ObjectList, adicionei um item e tentei limpar elas da memoria:
Trecho do código:
  tolRectMenuItemProntuario := TObjectList<TRectangle>.Create;
  tlLabelDadosPaciente := TObjectList<TLabel>.Create();
  tlLabelDadosPaciente.Add(lbTituloConvenio);
  tolRectMenuItemProntuario.Add(rtMenuItemAnamnese);
  tolRectMenuItemProntuario:= nil;
  tolRectMenuItemProntuario.DisposeOf;
  tlLabelDadosPaciente := nil;
  tlLabelDadosPaciente.DisposeOf;

Entretanto ao deletar tentar deletar a tlLabelDadosPaciente, a TObjectList< TLabel>, o sistema da erro:
"Project AppSIGMedOffLine.exe raised exception class EInvalidPointer with message 'Invalid pointer operation'."
Existe alguma forma diferente de deletar um TObjectList< TLabel>, pois eu estou utilizando da mesma forma os dois ObjectList, mas só o TLabel da erro.
Comment: Seria bom adicionar um exemplo mínimo e completo para que alguém pudesse reproduzir o que você está encontrando...
Answer: Você está atribuindo nil para a variável antes de executar o DisposeOf. Você teria de fazer essa atribuição somente após executar o método de liberação da memória. Ainda assim, acho que você deve  chamar o método .Free ao invés do Dispose. E também, ao criar TObjectList passe false como parâmetro. Se fizer assim, TObjectList não irá destruir os objetos quando ele mesmo for destruído. Passe true apenas se você cria os objetos em tempo de execução e/ou deseja que a lista os destrua.


Debugging line by line in c#

Question: I found on microsoft site that if I want to debug a program line by line I need to press F11.
If I press F11 I obtain (in a new form named Program.cs):
     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Windows.Forms;

     namespace WindowsFormsApplication1
    {
      static class Program
     {
    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    }
    }

They add that "When stepping through code, the line that is about to be executed is highlighted". In my case is highlighted:
       Application.EnableVisualStyles();

Should I choose another line?
Then, they tell to choose Stop Debugging to make the code editor writable.
If I follow this steps, I don't see any modifications. Should I see a new form in which the computer debug line by line? Should I do another thing?
I'm sorry if my question seems stupid. Please understand me that I am a begginer to C#.
Thank you so much!
Comment: See http://www.hermetic.ch/cfunlib/debug.htm Applies to VS also
Comment: Are you sure you understand what does "debugging" stand for? What exactly are you trying to achieve?
Comment: I was trying to achieve an "instruction by instruction". I didn't work with this way of debugging, so I didn't know anything about it. Because of help given by everyone, now I know to use it.
Answer: Your question has less relation to concrete language (C# in the tag) and much more about Visual Studio environment.
You press F11 to execute not line by line, but instruction-by-instruciton, cause if you immagin the code like  this:
if(condition) { x++; DoSomething(); ...}, on press of F11 it will not jump all this line but will execute

first if
after x++
after DoSomething(..)

and all this is on the same line in your code, but for compiler these are different instructions.
If you want to make editor Editable, it's enough to press Pause button. But by clicking Pause button, in case if in the scope of the current function there is no any lambda expression, you will be able to change the code just in Pause, they call this feature Edit and Continue
Hope this helps.
Comment: that's what I want: to execute instruction by instruction. I insert a simple breakpoint, I pressed F11 but I don't see the status of my variable. Where can I see it?
Comment: You can see them in [WatchWindow](http://msdn.microsoft.com/en-us/library/0taedcee.aspx), by dragging or writing down variables inside, [Locals Window](http://msdn.microsoft.com/en-us/library/a6td98xe(v=vs.100).aspx),or simply when the program in Pause state, over the mouse over any variable in the current execution scope, and you will see the tooltip-window.
Comment: Thank you very much! I found it!
Comment: @Bogdan: in code provided there is nothing to modify actually. You need to write at least some "Hello world" program. Check out examples on internet, it's impossible to explain everything in one answer.But it's not complicated
Comment: @Bogdan: if your program blocks at some point, and you don't know where: run the program, get to the point when it blocks and click "Pause" in `Visual Studio`, the row/function/iteration where the program blocked will be hitted, cause that is the instruciont that currently running.
Comment: How could I click Pause? Where is it?
Comment: @Bogdan: there is || button like this. I think you need definitely read this: [Debugging Tips with Visual Studio 2010](http://weblogs.asp.net/scottgu/archive/2010/08/18/debugging-tips-with-visual-studio-2010.aspx)
Answer: I think you need a few tips on how debugging works:
First of all, you should insert a simple breakpoint (F9 in Visual Studio) somewhere in the code you want to debug. Let's say you have a Windows Form Application, with a Form called Form1. In this form you have a Button which, when clicked, does something. You would have something like this:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        doSomething(...);
    }
}

To stop the execution of the program when you click the button (so you can see exactly what's happening), you can put a breakpoint on the click event. Once you have the breakpoint there, every time the click event is fired, the program will stop, and you will be able to run it step-by-step.
By running it step-by-step, you can see the status of your variables and the data you have stored. So you can locate where your code starts to behave differently from what you expected (what is usually called a bug).
To do so, you can step through the program procedure by procedure (F10) or instruction by instruction (F11). F10 will jump over function calls, executing them until they finish. F11 will enter into function calls, executing step by step every instruction in them.
Comment: I followed your steps until I pressed F11. Then, my first instruction from button1_Click became highlighted.Where I can see the status of my variables? Thank you!
Comment: while you are stopped, you can show the data of the scope clicking on Debug>Windows>Automatic. I'm not sure if it's called like this, as I have VS in spanish, not in English
Comment: in case it helps, here's what it looks like in my version: [link](http://i.imgur.com/yKeLG.jpg)
Comment: In English Version Debug->Windows : Output and Immediate. But neither help, unfortunately.
Comment: You can also use the "Inspection" window. There you can write any function call and it will show the result of it (care here, because if the function modifies anything, it will be modified)
Comment: Thank you very much for your help! (English version has Windows -> Watch Windows)
Answer: You should mark a debug point (or breakpoints), and then start debugging your program. Is not recommended, in my opinion, to start debugging line by line your program, you should debug just the parts that throws exceptions, and for that you mark breakpoints on your program (How to: http://msdn.microsoft.com/en-us/library/k80ex6de.aspx). When your program reachs that line, the debugger starts an detail debug line by line if you want.

Debugging line by line in c#


How to render full profile2?

Question: I am tring to load a full profile2.
I a trying the following code
<?php
$uid = user_load($node->uid);
$profile2_p = profile2_load_by_user($uid, 'profile2_profile');
print render($profile2_p);
?>

I get an error saying object can't be used as array.
If I print_r $profile2_p then I get an array relating to the correct profile2 entity. How can I render this entity?
Thanks
Answer: Looks like you can get a renderable array using profile2_view():
/**
 * View a profile.
 *
 * @see Profile::view()
 */
function profile2_view($profile, $view_mode = 'full', $langcode = NULL, $page = NULL) {
  return $profile->view($view_mode, $langcode, $page);
}

https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L1084
See also that modules hook_user_view() which does the same:
https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L399
/**
 * Implements hook_user_view().
 */
function profile2_user_view($account, $view_mode, $langcode) {
  foreach (profile2_get_types() as $type => $profile_type) {
    if ($profile_type->userView && $profile = profile2_load_by_user($account, $type)) {
      if (profile2_access('view', $profile)) {
        $account->content['profile_' . $type] = array(
          '#type' => 'user_profile_category',
          '#title' => $profile_type->getTranslation('label'),
          '#prefix' => 'type . '">',
        );
        $account->content['profile_' . $type]['view'] = $profile->view($view_mode);
      }
    }
  }
}

With a single entity in your code, you can:
render($profile2_p->view($some_view_mode));

How to render full profile2?


Verificação de HTTP(200) em PHP

Question: Eu fiz minha verificação assim, só que no meu deu um erro e em outros sistemas de verificação não deu. Gostaria de saber aonde foi que eu errei?
 $host = 'IP do HOST';
 $conectado = @fsockopen($host, 80);

 if (is_resource($conectado)) {
    print 'online';
 }else{
    print 'offline';
 }

Abaixo meu sistema e outro sistema verificado.
Comment: Você está utilizando `curl_init` ? Ou você saber se sua página está retornando o status 200?
Comment: Pois é eu tentei fazer via CURL mais minha hospedagem de teste não permite eu acho.
Comment: Eu quero enviar um comando para uma pagina para me retornar o valor 200.
Comment: Utilize [**curl_getinfo**](http://php.net/manual/pt_BR/function.curl-getinfo.php)
Comment: Não aparece nem curl_getinfo(); como tbm não aparece phpinfo();
Comment: da o erro 404 na pagina.
Comment: Já tentou verificar a resposta com o [**stream_get_meta_data**](http://br.php.net/manual/pt_BR/function.stream-get-meta-data.php) ?
Comment: Como faço isso?
Comment: Se possível [edit] sua pergunta e adicione como você está fazendo. Fica mais fácil mostrar uma solução.
Comment: Pronto alterei, tentei ser o mais claro possível.
Comment: No meu sistema so voltou as 14:40 no outro sistema de verificação nem caiu.
Answer: Para utilizar o fsockopen, você precisa remover o schema (http://) e a barra no final.
Exemplo:
$host = 'pt.stackoverflow.com';
$conectado = fsockopen($host, 80);

if (is_resource($conectado)) {
    print 'online';
}else{
    print 'offline';
}

Alternativas
Além do fsockpopen, você também pode utilizar fopen e curl.
Exemplo com fopen:
$host = 'https://pt.stackoverflow.com/';
$conectado = fopen($host, 'r');

@$result = @stream_get_meta_data($conectado);

if (is_resource($conectado) && strpos($result['wrapper_data'][0], "200") !== false) {
    print 'online';
}else{
    print 'offline';
}

Exemplo com curl:
$host = 'http://pt.stackoverflow.com:80';

ob_start();
$ch = curl_init($host);
curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
ob_end_clean();

if( $info === 200 ) {
    echo "Offline";
} else {
    echo "Offline";
}

Comment: Eu errei, vou alterar na pergunta. Pq no meu sistema não tem "/". E com fopen e curl não funciona no meu sistema de testes.
Comment: Consegui, eu estava errando mesmo numa coisa no meu código o seu me fez ver. Obrigado a todos, pela ajuda

Verificação de HTTP(200) em PHP


Lower semi-continuity of particular function

Question: Let $F : \mathbb{R}^n \rightrightarrows \mathbb{R}^n$ be a set-valued map, locally bounded, upper semi-continuous, and taking nonempty, convex and compact values. Let $f : \mathbb{R}^n \to \mathbb{R}$ be defined by
\begin{equation}
f(F(x)) = \min_{y \in F(x)} \lVert y \rVert.
\end{equation}
How can I show that the map $x \mapsto f(F(x))$ is lower semi-continuous?
Comment: What you want to prove is that the epigraph is closed. Does that help you?
Answer:
What you have: Set-valued upper semicontinuity is defined as the openness of $\{ x : \phi(x)\subset U\}$ for every open set $U$.
What you want: The lower semicontinuity of $f\circ F $ means that for every $r$, the set $\{x:f(F(x))>r\}$ is open. Let's rephrase this to be more similar to 1): for every $r>0$, the set $\{x:F(x)\subset \{y:|y|>r\}\}$ is open. Note this relies on the compactness of $F(x)$.

Now it should be clear that 1) implies 2). The assumption that $F(x)$ is convex is redundant.


Rest API Request Param and Path Variable

Question: I have to invoke a Get service with the below URL. The URL is a mix of Path variable and Request Param. Right now the URL is not getting constructed properly. Any suggestions?
Below is how i have tried and the actual output from Postman.
Sample:
@GetMapping(value = "/{abc}/commPrefsConsents/fieldOptions")
public ResponseEntity<String> getIndividualApi(@PathVariable(value = "abc") String abc, @RequestParam(required = true) String fieldOptions)

Actual URL:
http://localhost:8080/token/ca26e12dcfg-gdhska1/commPrefsConsents/?fieldOptions=preference-basic
URL getting created from Rest Controller :
http://localhost:8080/ca26e12dcfg-gdhska1preference-basic
Answer: The appropriate uri would be:
/ca26e12dcfg-gdhska1/commPrefsConsents/fieldOptions?fieldOptions=preference-basic
There is also a chance, that the mapping is affected by the @RequestMapping(value='foo') on the class level. If so, simply add foo to the beginning of your uri call.
Comment: I tried to define the context after the Path Variable and put those in a property file, so that it can be changed outside the code deployment.

Example:
in my application.yml:  hc.app.bu.request_param=/commPrefsConsents/?fieldOptions=preference-basic

Code:
System.out.println("URL :::" + sfmcConfig.getIndividualApi_url() + hcId + sfmcConfig.getRequest_param());


Using class algebra, if the intersection of classes A and B is the empty class, then how do you prove the difference of A and B is A?

Question: For reference, I'm self-studying Charles C. Pinter A Book of Set Theory. The exercise in 1.3 6b. calls for using only class algebra which is all the theorems used in that particular chapter. I have proof which starts out with the intersection of A and the complement of B being a subclass of A, and then deriving the subclass in the other direction. However, using just class algebra, I haven't been able to come up with a proof. I have tried working by starting with A-B, then to A intersect complement B, but using purely class algebra, I haven't been able to crack it. I've worked on this problem for awhile and looked at by using various theorems and the examples such as the one nearing the end of the chapter with this exercise. If someone could point me in the right direction, that would be greatly appreciated.
Answer: \begin{align*}
A - B
&= A \cap B' && \text{by definition}\\
&= \emptyset \cup (A \cap B') && \text{by an identity law}\\
&= (A \cap B) \cup (A \cap B') && \text{by hypothesis}\\
&= A \cap (B \cup B') && \text{by a distributive law}\\
&= A \cap \mathcal{U} && \text{by Pinter Thm 1.26(vii)}\\
&= A && \text{by an identity law}.
\end{align*}


Probability that event $A$ occurs but event $B$ does not occur when events $A$ and $B$ are mutually exclusive

Question: Events $A$ and $B$ are mutually exclusive. Suppose event $A$ occurs with probability $0.74$ and event $B$ occurs with probability $0.22$.

Compute the probability that $A$ occurs but $B$ does not occur.
Compute the probability that either $A$ occurs without $B$ occurring or $A$ and $B$ both occur.

Answers:

$\Pr(A \cap \neg B) = \Pr(A) + \Pr(\neg B)- \Pr(A \cap B) = 0.74 + 0.78 -(0.74 \cdot 0.78)=0.9428$
$\Pr([B \cap A] \cup [A \cap B])= \Pr(\neg B \cap A) + \Pr(A \cap B) = 0.78 \cdot 0.74 + 0.74 \cdot 0.22=0.74$

Is it correct?
Comment: What is your *definition* of mutually exclusive events?
Comment: That means very different from each other?
Comment: That's not a mathematical definition. One definition is $P(A \cap B) = 0$.
Comment: ohhhh!!!!!!  so for no.1 it should be 0.74+0.78?
Comment: Can a probability be $>1$?
Comment: No..................
Comment: Can you please tell me the final answer for both 1 and 2, i will work out the steps
Comment: You cannot use $P(A \cap B) = P(A)P(B)$ as the events are not independent.
Answer: Supposing, as is usual (e.g. here) that mutually exclusive means that $P(A \cap B) = 0$ we have that $P(A \land \lnot B) = P(A \setminus B) = P(A) - P(A \cap B) = P(A) = 0.74$.
The final one is then just $P(A)$ too. $A$ cannot occur at the same time as $B$.
Comment: Mutually exclusive *implies* that $P(A\cap B)=0$ which is enough here. The actual meaning of it is that $A\cap B=\varnothing$.
Comment: Thank you!!!!!!!!!!!!!!!!!!!!!
Comment: @drhab Quite. And so both parts are just roundabout ways of asking for $P(A)$. A bit confusing for the OP maybe.


How to override output of checkout page in Commerce

Question: I want to override the output of the order completion page. I need to include custom markup, as well as data from the order. As a matter of personal preference (and for organizational purposes), I'd rather do this in code, in my module, rather than in Rules. Can anyone point me in the right direction?
Comment: Are you familiar with coding in drupal using hooks and custom modules?
Answer: It looks like using hook_commerce_checkout_pane_info_alter(&$checkout_panes) or hook_commerce_checkout_page_info_alter(&$checkout_pages) would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary (hook_commerce_checkout_pane_info() and hook_commerce_checkout_page_info()). I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files.
Comment: Yeah, the code in commerce_checkout.checkout_pane.inc gives a good implementation example. I should be able to override the output with hook_commerce_checkout_pane_info_alter(). Thanks for the tip.


Simple Counter app crashing on start up without any error

Question: Background - I only started using android studio this morning, so I'm green as grass.
I'm trying to make a simple Counter app where it adds/subtract one from the total and then displays it. But for some reason the app just crashes on start up.
Here is my code - there are a couple more OnClickListener methods that I did not include, but they're all the same code.
Thanks in advance.
public class MainActivity extends AppCompatActivity {

Button counter1Up, counter1Down, counter2Down, counter2Up;
TextView counter1, counter2;

double lifeTotal1 = 20, lifeTotal2 = 20;

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

    counter1Up.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lifeTotal1 = Double.parseDouble(counter1.getText().toString());
            counter1.setText(String.valueOf(lifeTotal1 + 1));
        }
    });

    counter2Up.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lifeTotal2 = Double.parseDouble(counter2.getText().toString());
            counter2.setText(String.valueOf(lifeTotal2 + 1));
        }
    });

    counter1Down.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lifeTotal1 = Double.parseDouble(counter1.getText().toString());
            counter1.setText(String.valueOf(lifeTotal1 - 1));
        }
    });

public void setUI(){
    counter1Up = findViewById(R.id.counter2UpButton);
    counter1Down = findViewById(R.id.Counter1DownButton);
    counter2Up = findViewById(R.id.counter2UpButton);
    counter2Down = findViewById(R.id.counter2DownButton);
    counter1.setText("20");
    counter2.setText("20");
}
}

And this is what the Event Log shows:
1/19/2019
3:29 AM Gradle sync started

3:29 AM Project setup started

3:29 AM Gradle sync finished in 2 s 979 ms

3:29 AM Syncing only active variant
                You can disable this experimental feature from
                File → Settings → Experimental → Gradle → Only sync the active variant

3:29 AM Executing tasks: [:app:generateDebugSources]

3:29 AM Gradle build finished in 780 ms

3:51 AM Executing tasks: [:app:assembleDebug]

3:52 AM Gradle build finished in 13 s 75 ms

Comment: Post your error logs.this is build logs.Bottom of android studio you can see buttons such as Run-Build-Terminal-Logcat etc. Click logcat And copy what it say.
Answer: welcome to the world of Android development.
I'm not sure if you've introduced yourself to the debugging an Android application yet, but the output of the event log might not help in this case. Google does provide a ton of information on this topic, and the very first thing you should familiarize yourself with is the Android debugger and its output view in Android Studio. You may want to start learning here: https://developer.android.com/studio/debug/
Regarding your problem, I think you've ran into a classic NullPointerException in line 5 of your setUI() method where you're accessing the TextView variable counter1 without retrieving it from the layout using findViewById() just like in lines 1-4 of the very same method.
Comment: Ahhh I knew it was gonna be something super obvious, thanks for the assistance and for the helpful link!
Answer: You haven't initialized your textviews counter1 and counter2.
Initialize both the variable before calling methods on them.


How to archive drupal forums?

Question: How can I add archive state to drupal forums so that:

They are not visible in search results
They are shown in a different container
They are visible only to some users based on user-roles

I don't want to unpublish them-
I also want a spam state to differentiate unpublished and spam posts
Comment: Sorry, i misread "forum" for "form" and I tought you were meaning "webform" module.. sorry!
Comment: Edited my answer
Answer:
They are not visible in search results

http://drupal.org/project/search_config

They are shown in a different container

Templating system, or blocks, or panels

They are visible only to some users based on user-roles

EDIT
Those 2 steps are equal, but becose my understanding problem the last point can be different.
In <code>/admin/people/permissions</code> you should have the options to allow only some roles to access the forms nodes.
Comment: I am still confused, what would be the state of forum topic and webform funda?
Comment: ooops sorry my bad, i misread "forum" for "form"..

How to archive drupal forums?


How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Question: In SQL Server 2008 Management Studio, when I right click on a database table and choose Select Top 100 Rows, I can then e.g. easily add a ORDER BY statement to the SQL. That works fine.
But when I do choose Edit Top 200 Rows, I don't have the ability to alter the SQL (which makes it hard to find and edit a record just added in the 10,000 that are there.
I am quite sure I was able to do this in SQL Server 2000.
Is there any way in SMSS 2008 to alter the way the records are displayed when editing records?
Answer: If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.
It's the SQL button on the following image:

In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.
Comment: To refresh the results after editing the query, you need to right-click and select `Execute SQL` (Or use the keyboard shortcut Ctrl+R)
Comment: Is it possible to have Pane -> SQL as default when using "Edit top 200 rows"?
Comment: This answer its even better, it allows you to actually Edit the query
    SELECT top 500 ***
    SELECT top 1000 *** WHERE ***
Comment: Great answer!!--very useful b/c it shows an EDIT grid.  afaik it's completely undocumented. (also nowhere else in ssms do you get an edit grid with a composable sql of the rows you want in the edit grid). This shouldn't be so buried in the SSMS gui. (Still works on the latest ssms and sql server 2019.)
Comment: this is perfect!  Late to the game but this is still a really helpful answer
Answer: You can also change the pop-up options themselves, to be more convenient for your normal use.  Summary:

Run the SQL Management Studio Express 2008
Click the Tools -> Options
Select SQL Server Object Explorer . Now you should be able to see the options

Value for Edit Top Rows Command
Value for Select Top Rows Command

Give the Values 0 here to select/ Edit all the Records

Full Instructions with screenshots are here:  http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html
Comment: Not found http://m-elshazly.blogspot.com.es/2011/01/sql-server-2008-change-edit-top-200.html
Comment: @nag - This is a good answer for permanent changes to the buttons, but sometimes I want to make changes to a small subset of rows while looking at others. The answer by David Hall makes this possible by simply adding `Where ID in (1,2,3,4,5)` or something similar.
Answer: Very quick and easy visual instructions to change this (and the select top 1000) for 2008 R2 through SSMS GUI
http://bradmarsh.net/index.php/2008/04/21/sql-2008-change-edit-top-200-rows/
Summary:

Go to Tools menu -> Options -> SQL Server Object Explorer
Expand SQL Server Object Explorer
Choose 'Commands'
For 'Value for Edit Top  Rows' command, specify '0' to edit all rows
Comment: This is the only option that seemed to work in the SQL Server Management Studio in 2020
Answer:
Follow the above image to edit rows from 200 to 100,000 Rows
Answer: Ctrl+3 in SQL Server 2012. Might work in 2008 too
Answer: in SQL 2017 You can do it more easily  in the toolbar to the right  just hit

the SQL  button  then its gonna apear  the query with the top 200 you edit until the  quantity that You want and Execute the query and  Done! just Edit
Answer: Similar to David Hall's response, if you are a non-coder, it may be easiest to right-click within results, then choose Pane > Criteria. This allows you to adjust sort, add filters, etc... without adjusting SQL code.
Answer: The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:

Go to Tools in top nav
Select options, then SQL Service Object Explorer (on left)
On right side of panel, click into the field that contains 200 and change to 300 (or whatever number you wish)
Click OK and voila, you're all set!


Accessing private tumblr blog posts in iOS

Question: I am using Tumblr API v2 to retrieve posts from a private blog. I used OAuth and when the user is the admin or a member of the blog, posts can be retrieved. I believe that the posts can be accessed only by a team member. Is my belief true? Is there any official source stating so. Is there a way to access the blog via API if i know the password?
Answer: Since there is no response to my question, guess i have to stick to my own findings
https://groups.google.com/forum/?fromgroups#!searchin/tumblr-api/Private$20Blogs/tumblr-api/qySxi23DdXI/w0NB0qxxrGIJ
this is a link i found that states that we should perform a complete oauth for accessing private blogs. Our idea was to keep the source of posts secret. So we managed to get the oauth token and secret of the admin of the blog , and then we hardcoded these two strings so that we have all the 4 keys and we can access the posts from the private blog and without the user knowing about it (without the actual oauth). we had contacted tumblr and made sure that the auth token and secret donot change.
About accessing the blog if password is known, didnt find anyway to do so. Dont know whether it exists.


Why is the Dominant 7th based on the Diatonic Scale?

Question: I understand that the Dominant 7th chord as a structure is called like that because its chord structure is playable from the Dominant in a Diatonic scale.
However, I noticed that the same structure is playable in the Subdominant of the Melodic Minor scale. In that case it would theoretically be called a Subdominant 7th chord.
So why is the chord's name based on its playability in the Diatonic Scale and not on some other scale?
Answer: The major scale is used as a yardstick in music theory, because there is only ONE form of the major scale.  This is convenient, because it leads to consistent labeling: C-A is always a major 6th interval, CEGBb is always a dominant 7th chord , etc. (Edit: I'm talking about the chord structure rather than where it occurs - some will call it a maj/m7 chord if the root is a tone other than the dominant)
If we used the scale of the key instead, we would end up with different labels for the same thing: C-A would be a major 6th interval in C melodic minor, but an augmented 6th in C harmonic minor.
By the way, there are no "8th" chords, because 8 is the same as a root.  Chords are always named from the scale of the root. Even if you were using your proposed method of naming in relation to the scale of the key, the 7th note of the chord isn't the 8th note of any scale based on the chord's root.
Comment: Strictly speaking, "dominant" refers to the scale degree, not the chord type.  It could be major, minor, some type of seventh, an extended chord, etc.  That's why some people call a 1-3-5-b7 chord that falls on a different sale degree a "major/m7" chord, because it's not on the dominant scale degree.
Comment: Thanks for the info. And you're right about the 8th, I have corrected it. I have one other question. Is it correct that a "dominant chord" (without the 7th) is not necessarily always a Major triad but can also be a Minor triad depending on the scale?
Comment: The idea that major and minor intervals are so called because they derive from major and minor scales is attractive but incorrect.  Rather the opposite is in fact the case: the distinction between major and minor intervals was made centuries before people were talking about scales or keys.  So the statements "the major scale is used as a yardstick" and "C-A would be a major 6th interval in C melodic minor, but an augmented 6th in C harmonic minor" are not correct.
Answer: In a comment you ask

Is it correct that a "dominant chord" (without the 7th) is not necessarily always a Major triad but can also be a Minor triad depending on the scale?

Perhaps, but this question has music history a bit backwards.  First there were intervals, then chords, then scales and keys.
There is a common misconception that scales and keys are synonymous.  But the three forms of minor scale do not correspond to three forms of minor key.  Minor tonality came first, but, long before the concept of keys was developed, there arose a fashion for raising the leading tone in the final cadence.  As harmony developed, long after that fashion was firmly established, this gave rise to a rule that the dominant chord in a minor key would have a raised third degree.  A few centuries later, that gave rise to the (somewhat artificial) idea that the minor scale has three forms.
While it's true that "dominant" arose as a label denoting the fifth degree of the scale, the term has come to mean the function associated with that scale degree in standard harmonic practice, and that function is the same in both major and minor tonality.  If a piece in a minor key has a minor chord on the fifth scale degree, it is likely to be called the "minor dominant," since without that qualifier most would assume a raised third.
Comment: Ah that explains why some sources define the dominant chord always as a major triad. Sorry but I'm still not getting what the difference is between scales and keys. Could you please elaborate further on that?
Answer: The dominant seventh chord got its name from its frequent use as the dominant chord, strongly driving the harmony towards the key's tonic chord. https://en.wikipedia.org/wiki/Dominant_seventh_chord
It's not a law of nature, not physics or mathematics. It's about culture, history, people. https://en.wikipedia.org/wiki/Humanities
Answer: First some context. Western music began with monophonic Gregorian chant.  The most common note sung was the 5th degree, which led to it being named the 'dominant'.
Western music derived it's modal system from the Greeks and others, using a division of the octave into 7 distinct notes using only whole and half steps. Renaissance composers routinely sharped leading tones at cadences and lowered the fourth in the Lydian mode, and effectively only the Aeolian and Ionian modes were in general use by the Baroque, and became known as the natural minor and major scales, respectively.
In the early 1700's, Rameau published "A Treatise on Harmony" in which the modern chord classification was documented, including the building of chords in 3rds and using the highest chord note above the 5th as part of the chord name.  This classification was done based on the major and natural minor scales.
Since traditional theory is based on the major scale, and the only degree in that scale that a major chord with a flatted 7th occurs naturally is on the 5th degree (dominant), the chord structure is called a Dominant 7th.
Dominant 7ths can be played on other degrees, and are often called 'secondary dominants', but they have one or more notes in the key altered in order to get the root, major 3rd, perfect 5th, minor 7th structure.
The answer is that the name 'Dominant 7th' is given because the structure of a dominant 7th only naturally occurs on the 5th degree.
Comment: The dominant of the Phrygian mode is the sixth degree, not the fifth, and the dominants of the plagal modes are different still.  The explanation of the fifth degree being called the dominant isn't complete without mentioning that minor tonality developed from the Dorian mode and major from the Lydian and Mixolydian, namely the three modes in which the dominant _was_ a fifth above the final.
Answer: There must be many,many more times the dominant seventh harmony is used in major rather than minor keys, over several centuries, so it's far more commonplace. And the same harmony works in minor, using the 5 of the key as root, anyway. True, the same harmony can be found from the melodic minor notes (ascending), so common usage made it the 'go to' dominant seventh chord.
Answer: Well, we had to call it SOMETHING!  It's logical to go for the most common possibility.
'Dominant 7th' has come to mean a particular chord shape, not necessarily a description of harmonic function in any particular context.
In a simple Blues - using C7, F7 and G7 chords - all those chords might be classed as 'dominant 7th' shapes, though only one of them is the actual dominant 7th chord of the piece.
We might expect that a major 7th chord - C, E, G, B♮ - would get classed as a 'Tonic 7th' shape.   But, somehow, that hasn't caught on.
Comment: I guess it has something to do with the fact that a Major 7th chord as a structure  is playable from 2 different degrees in the Diatonic scale (Tonic and Subdominant). Hence it is has to be specified by giving the chord structure a more general name, e.g. Major 7th.


IIS Rewrite rules for PHP Zend application migrated from Apache

Question: Versions:
PHP 5.5
Zend v 2.5
IIS V 10
Hi, I have migrated an apache website to IIS with a simple copy and paste and setup rewrite rules from the HTAccess file.  The site all works fine accept when a modal with a button that has <a href="#" is clicked.  The button should simply close the modal but instead it takes you back to the home page.  I imagine the rewrites are wrong but I have searched everywhere and nothing seems to change the behaviour.
Rewrite Rules:
 <rule name="Imported Rule 1" enabled="true" stopProcessing="true">
                      <match url="^.*$" />
                      <conditions logicalGrouping="MatchAny">
                          <add input="{REQUEST_FILENAME}" matchType="IsFile" pattern="" ignoreCase="false" />

                          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" pattern="" ignoreCase="false" />
                      </conditions>
                      <action type="None" />
                  </rule>
                  <rule name="Imported Rule 2" enabled="true" stopProcessing="true">
                      <match url="^.*$" />
                      <action type="Rewrite" url="/index.php" />
                  </rule>

I tried many different rules on the internet but nothing changed.  I tried ignoring # in the rules which did nothing but I am unsure if my rule was correct.
Comment: According to your description, I couldn't understand your requirement clearly. your problem seems to be with the button, how did you define your button? or you can just tell me which url you want to rewrite.
Comment: Hi, this button should do nothing but close the modal.  When clicked however it redirects back to index.php, I believe the rewrite rules cause this and need to prevent this action.  Button HTML:  `Ok`
Answer: If you wan to rewrite to index.php when click the  tag, you can try to use outboundrule in iis. I have a test.html page with only  tag in it, when I click on it, it will add a "#" end of the url, so I use the outbound rule to rewrite it to index.php.
<rewrite>
   <outboundRules>
        <rule name="CustomRedirect">
           <match filterByTags="None" pattern="#" />
           <action type="Rewrite" value="index.php" />
        </rule>
   </outboundRules>
</rewrite>

This is test result:


Drupal 6 - Grouping Modules together

Question: I have been creating a lot of code in the past few months for my Drupal 6 website and have since created about 20 modules of code that all pretty much go together.
I know we can group modules together in a folder, but am wondering what impact this will have if I do this on already deployed modules.
Is it possible for me to simply create a new folder in the sites/all/modules folder and move all my modules in this new folder? Will Drupal handle this properly?
Answer: Grouping modules is allowed in Drupal, when the modules are not already modules. Because, the modules are registered in System table by the location of the module. So, Changing the folder structure will result in fatal errors.
If you would like to change the folder structure then you need to disable the modules and uninstall them. After that, you can re-enable them after changing the folder structure by grouping them.
Note: Make sure you won't lose any data when you un-install the custom modules. Take a backup of database and source code before doing any changes for safe side.
Comment: Not really. You can move around modules while enabled provided other modules are not dependent on module being moved to avoid call to undefined function fatal errors. And its not required to uninstall modules disable/enable will do

Drupal 6 - Grouping Modules together


Tunneling HTTP traffic from a particular host/port

Question: I'm trying to figure out how to access from my development machine (Devel) to a third party web service (www.domain.com) which I am not allowed to directly contact using my office IP address.
Here's a basic diagram (i'm not allowed to post images...):
http://yuml.me/diagram/scruffy/class/%5BDevel%5D-%5BA%5D,%20%5BA%5D-%5BB%5D,%20%5BB%5D-%5Bwww.domain.com%5D
The only machine allowed to access that service is B (production server) but I do neither can directly access it from my development machine (Devel).
So in order to access the web service I have to ssh into A, and then from A to B to access www.domain.com
Is there any way of tunneling traffic from B to A and then back to my development machine so I can directly access www.domain.com without having to ssh into every box?

Devel: My development machine.
A, B: Linux servers. I own root access on both.
B: Production server
www.domain.com: Third party HTTP API production server uses.
Answer: Yes it is. I do not do this on a regular basis, so when I need to I look up my bookmark on this, which is here. Rather than to quote the article, just follow the very simple examples. They should be easy to set up for you.
Hope this helps!
Comment: However you may want to first of all work with the networks and sysadmin teams to figure out why they have put in place this block so that you're not violating any policies which you're not meant to be breaking.
Comment: Ok, tried it and it actually worked, but HTTP request headers were wrong and apache returned a forbidden response. So I guess I need to find another approach.

@DaveG, there's no sysadmin teams here... and I already asked for a VPN account or whatever and they provided nothing. Or office has no static IP address so there's no way of doing things right.


Is it correct that not all projections are self adjoint?

Question: Is it corrrect that not all projections on $(\mathbb{R}^n,\langle,\rangle)$(linear maps with $P^2=P$) are self adjoint, although all orthogonal projections are?
Comment: It doesn't make sense to ask if a linear map of a vector space is self-adjoint. We need a scalar product (or at least a non-degenerate bilinear form) in order to define adjoints.
Answer: Hint: consider the matrix
$$P = \begin{pmatrix}
1 & 1\\
0 & 0
\end{pmatrix}$$


Big-O multiplied by Big-Theta

Question: I have an algorithm that iterates for $\Theta(n)$ steps. Each step has a complexity $O(n^2)$.
The complexity of the algorithm is then given as $\Theta(n) \times O(n^2) = ?$
Is it valid to multiply Big-Theta and Big-O? If so, what is the product of the $\Theta(n) \times O(n^2)$? Since Big-O ignores all lower-order terms, my gut is telling me that it is just equal to $O(n^2)$.
Comment: It would become $O(n^3)$
Answer: We can keep estimation only from above (right):
suppose we are working with non negative sequences and we have $f(n) \leqslant C \cdot n^2$ together with $C_1 n \leqslant g(n) \leqslant C_2 n$. Unique which we can state is $fg \leqslant C_0 n^3$. We cannot set left bound and say that $fg \in \Theta(n^3)$. Counterexample: $f(n)=n$ and $g(n)=\frac{1}{n^2}$. Obviously $f \in \Theta(n)$ and $g \in O(n^2)$, but product tends to zero.
So we can only state $$\Theta(n) \cdot O(n^2) \subset O(n^3)$$
Answer: It will be $O(n^3)$, and you cannot do any better as $f(n)= n$ is $\Theta(n)$ and $g(n) = n^2$ is $O(n^2)$ and their product is even $\Theta(n^3)$.
Comment: $\Theta(n) \cdot O(n^2)$ is not $\Theta(n^3)$, see counterexample in my answer, please.
Comment: @zkutch I also give a counterexample. I say it's $O(n^3)$ too.
Comment: You are correct, of course, when you are saying "it's $O(n^3)$". Here we are together. But I mean your words "..and their product is even $\Theta(n^3)$" - this one is not correct.
Comment: @zkutch $n^3$ is $\Theta(n^3)$ is in't it?
Comment: $\Theta(n) \cdot O(n^2)$ is not $\Theta(n^3) $ you are not agree?

Big-O multiplied by Big-Theta


Como obter índice da iteração atual de um foreach?

Question: Normalmente, a fim de obter o índice da iteração atual dentro de um foreach, faço da seguinte maneira:
int i=0;
foreach (var elemento in list)
{
   // Qualquer coisa
   i++;
}

Acredito que existam outros métodos para obter o índice da iteração (até mais "bonitos" que o apresentado), quais são?
Comment: @NicolasBontempo minha dúvida se limita ao `foreach` mesmo.
Comment: utilizar o for normal não é uma opção?
Comment: Relacionada: [Como determinar o último elemento de uma lista em um foreach?](http://pt.stackoverflow.com/q/138009/18246)
Answer: Na verdade se precisa realmente do índice, o certo é usar o for.
Se não quer usar a ferramenta correta para o problema, a solução mais óbvia é a apresentada na pergunta.
Fora isso a solução que o pessoal costuma fazer é usar LINQ, o que eu acho um exagero para o problema e muito raramente é uma solução melhor que as anteriores em qualquer análise que se faça - se fizer uma análise geral, duvido que ela seja boa em qualquer situação. Seria algo assim:
foreach (var pair in list.Select((x, i) => new {Index = i, Value = x})) {
    WriteLine($"{pair.Index}: {pair.Value}");
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Acho menos legível, menos performático e não consigo ver qualquer ganho.
Alguns preferem criar alguma abstração em cima disso, como um método de extensão que esconda um pouco os detalhes de implementação, ou uma classe que trate disto. Em raros casos acho isso adequado. Dependendo do caso (onde um método substitui o laço) muda a semântica e poucos programadores sabem lidar com isso direito. Acaba sendo um exagero para evitar o uso óbvio e simples.
O que poderia deixar um pouco melhor, algo assim:
foreach (var pair in list.IndexPair()) {
    WriteLine($"{pair.Index}: {pair.Value}");
}

public static class IEnumerableExt {
    public static IEnumerable<T> IndexPair(this IEnumerable<T> enumerable) {
        return enumerable.Select((x, i) => new {Index = i, Value = x});
    }
}

Já vi algumas soluções tão esdrúxulas que me recuso postar aqui.
Comment: @ramaral espero que não :) Eu vi algumas pessoas postando algo assim, mas acho que só a título de curiosidade. Tem linguagem que não tem mais o `for`, e pior não tem um `foreachindexable` que aí até faria sentido para uns casos, mas não para todos, acho um erro. Acho bom evitar o `for` quando dá, mas não a qualquer custo.
Comment: Quando eu aprendi linq, fiquei animado pra usar em tudo. Hoje em dia, sabendo das possíveis perdas em uma implementação falha(vamos ser sinceros e concordar que 90% dos que usam Linq não sabem o que ele faz de verdade), prefiro usar em casos em que o `foreach` não consegue fazer direito ( joins / predicated wheres, etc).
Bom pra saber, ... não muito bom pra implementar em produção. Opinião minha.
Comment: @EricWu virei seu fã :D
Answer: O foreach é uma forma de loop mais elegante, para iterar sobre elementos de uma collection em várias linguagens. Na linguagem C# é usada para iterar sobre coleções que implementam o IEnumerable. Então ele vai chamando o método GetEnumerator o que retorna um Enumerator. Nesse Enumerator temos as propriedades:
MoveNext() atualiza o Current com o próximo objeto

e
Current retorna o Enumerator atual

Então, o conceito de índice no foreach não é encontrado. Ao invés de utilizar uma variável fora do foreach para controle do índice, é mais razoável em minha opinião utilizar o for normalmente:
for (int i = 1; i <= 5; i++)
{
   list[i];
   Console.WriteLine(i);
}

Answer: O foreach não possui conhecimento do índice atual para expô-lo de uma maneira elegante, você tem que controlar uma variável manualmente mesmo. Isso acontece porque o foreach é uma estrutura independente de um tipo de dado que precise trabalhar com indexamento por números. Ele trabalha somente sobre a interface IEnumerable e IEnumerator.
O fato de não possuir um índice no foreach faz todo o sentido, visto que você pode implementar usar o foreach em estruturas que não possuem indexamento, como uma LinkedList
Answer: Não sei é a maneira mais eficaz e performática, porém seguindo a analogia para realizar a interação em cima de uma lista em python, podemos obter o índice em um foreach em c# e interar utilizando este índice em cima da lista da seguinte forma.
Exemplo:
 var lista = new List<int>(){ {100}, {200}, {300}, {400}, {500}, {600}, {700},
                              {800}, {900}, {1000}
 };
foreach(var index in Enumerable.Range(0, lista.Count()).ToList())
    Console.WriteLine("Index item: "+ index + " valor item na lista: " +
                       lista[index]);
}

Desta forma ao invés realizar a interação através do foreach em cima da lista diretamente, cria-se uma nova lista de índices através do (Enumerable.Range) de 0 até o tamanho total da lista, assim criando uma lista de índices de 0 até o tamanho da lista em um intervalo de 1 em 1.
Sendo assim ao invés de interar diretamente em cima da lista desejada, faz-se a interação em cima da lista de índice onde cada índice ira corresponder a posição do elemento desejado na lista, assim sendo possível obter o acessar e  obter o índice do elemento da lista de forma similar a um for tradicional.
Segue exemplo no .NET Fiddle: https://dotnetfiddle.net/cDyfdg
Answer: Você usar o for para ter o controle da iteração, e usar ElementAt para pegar o valor
static void Main(string[] args)
        {
                var lista = new List<teste>() {
                    new teste("João", 12),
                    new teste("Maria", 12),
                    new teste("José", 12),
                    new teste("Carlos", 12),
                    new teste("Juliana", 12),
                };

                for (int i = 0; i < lista.Count(); i++)
                {
                    Console.WriteLine(lista.ElementAt(i).nome);
                }

                Console.ReadKey();
            }

            public class teste
            {
                public teste()
                { }
                public teste(string _nome, int _idade)
                {
                    this.nome = _nome;
                    this.idade = _idade;
                }
                public string nome;
                public int idade;
            }


How do you get the Oauth2 AccessToken after its creation from the Owin Api?

Question: If for some auditing reason I would be asked to store the AccessToken to Db after its creation, is there an Owin API Class that returns the AccessToken ?
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    //check user credentials
    ....
    context.Validated(ticket);
    //Where should I get the generated token?
    }
}

The only workaround I found is to create an Http filter in the Global.Asax that reads the output stream and get the Token from there.
Is there a more elegant way to get it directly from the Owin Api?
Answer: Sure you can but you need to use Microsoft.Owin.Security.OAuth version 3.0 not 2.1 and then override TokenEndpointResponse in class OAuthAuthorizationServerProvider as the code below
public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
    {
        var accessToken = context.AccessToken;
        return Task.FromResult<object>(null);
    }

Comment: on logout i need to clear the accessToken from my web API, please let me where it will stored.
Comment: Any ideas on how to change the access token? context.AccessToken = "newToken" doesn't see, to work as it doesn't have a setter.


How do you minimize "hinge-loss"?

Question: A lot of material on the web regarding Loss functions talk about "minimizing the Hinge Loss".
However, nobody actually explains it, or at least gives some example.
The best material I found is here from Columbia, and I include some snippets from it below.
I understand the hinge loss to be an extension of the 0-1 loss. The 0-1 Loss Function gives us a value of 0 or 1 depending on if the current hypothesis being tested gave us the correct answer for a particular item in the training set.
The hinge loss does the same but instead of giving us 0 or 1, it gives us a value that increases the further off the point is.
This formula goes over all the points in our training set, and calculates the Hinge Loss $w$ and $b$ causes. It sums up all the losses and divides it by the number of points we fed it.

where
This much makes sense to me.
What's confusing me is as follows:

How do you plot a hinge loss function?
How do you minimize it? Isn't the minimal always zero?
How should I understand the typical hinge loss graph? Are they just gross oversimplifications?
For example, the green line represents the hinge loss function you see in every image in a Google search for "hinge loss".

**Please, **Can someone provide (for the world) a simple example of hinge loss minimization? Let's say I have four negative points (blue circles) and four positive points (red squares). What would the loss function look like? How do I minimize (mathematically, and with intuition).
Knowing this would be a huuuge help for me, and probably for many others, as the resources on this popular topic are scarce. Thanks!
Comment: `For example, the yellow line represents the hinge loss function you see in every image in a Google search for "hinge loss".` None of those lines are yellow...
Comment: Damn my colorblindness... what is it? Green?
Comment: If you mean $\max(0,1-yf(x))$, then yes.
Answer: To answer your questions directly:

A loss function is a scoring function used to evaluate how well a given boundary separates the training data. Each loss function represents a different set of priorities about what the scoring criteria are. In particular, the hinge loss function doesn't care about correctly classified points as long as they're correct, but imposes a penalty for incorrectly classified points which is directly proportional to how far away they are on the wrong side of the boundary in question.
A boundary's loss score is computed by seeing how well it classifies each training point, computing each training point's loss value (which is a function of its distance from the boundary), then adding up the results.
By plotting how a single training point's loss score would vary based on how well it is classified, you can get a feel for the loss function's priorities.  That's what your graphs are showing— the size of the penalty that would hypothetically be assigned to a single point based on how confidently it is classified or misclassified. They're pictures of the scoring rubric, not calculations of an actual score. [See diagram below!]
At least conceptually, you minimize the loss for a dataset by considering all possible linear boundaries, computing their loss scores, and picking the boundary whose loss score is smallest.  Remember that the plots just show how an individual point would be scored in each case based on how accurately it is classified.
Interpret loss plots as follows:  The horizontal axis corresponds to $\hat{y}$, which is how accurately a point is classified.  Positive values correspond to increasingly confident correct classifications, while negative values correspond to increasingly confident incorrect classifications. (Or, geometrically, $\hat{y}$ is the distance of the point from the boundary, and we prefer boundaries that separate points as widely as possible.) The vertical axis is the magnitude of the penalty.  (They're simplified in the sense that they're showing the scoring rubric for a single point; they're not showing you the computed total loss for various boundaries as a function of which boundary you pick.)

Details follow.

The linear SVM problem is the problem of finding a line (or plane, etc.) in space that separates points of one class from points of the other class by the widest possible margin.  You want to find, out of all possible planes, the one that separates the points best.
If it helps to think geometrically, a plane can be completely defined by two parameters: a vector $\vec{w}$ perpendicular to the plane (which tells you the plane's orientation) and an offset $b$ (which tells you how far it is from the origin). Each choice of $\langle \vec{w}, b\rangle$ is therefore a choice of plane.   Another helpful geometric fact for intuition: if $\langle \vec{w}, b\rangle$ is some plane and $\vec{x}$ is a point in space, then $\vec{w}\cdot \vec{x} + b$ is the distance between the plane and the point (!).
[Nitpick: If $\vec{w}$ is not a unit vector, then this formula actually gives a multiple of a distance, but the constants don't matter here.]
That planar-distance formula $\hat{y}(\vec{x}) \equiv \vec{w}\cdot \vec{x} + b$ is useful because it defines a measurement scheme throughout all space: points lying on the plane have a value of 0; points far away on one side of the boundary have increasingly positive value, and points far away on the other side of the boundary have increasingly negative value.
We have two classes of points. By convention, we'll call one of the classes positive and the other negative. An effective decision boundary will be one that assigns very positive planar-distance values to positive points and very negative planar-distance values to negative points. In formal terms, if $y_i=\pm 1$ denotes the class of the $i$th training point and $\vec{x}_i$ denotes its position, then what we want is for $y_i$ and $\vec{w}\cdot \vec{x}_i+b$ to have the same sign and for $\vec{w}\cdot \vec{x}_i+b$ to be large in magnitude.
A loss function is a way of scoring how well the boundary assigns planar-distance values that match each point's actual class.  A loss function is always a function $f(y, \hat{y})$ of two arguments— for the first argument we plug in the true class $y=\pm 1$ of the point in question, and for the second $\hat{y}$ we plug in the planar distance value our plane assigns to it.  The total loss for the planar boundary is the sum of the losses for each of the training points.
Based on our choice of loss function, we might express a preference that points be classified correctly but that we don't care about the magnitude of the planar-distance value if it's beyond, say, 1000; or we might choose a loss function which allows some points to be misclassified as long as the rest are very solidly classified, etc.
Your graphs show how different loss functions behave on a single point whose class $y=+1$ is fixed and whose planar distance $\hat{y}$ varies ($\hat{y}$ runs along the horizontal axis). This can give you an idea of what the loss function is prioritizing. (Under this scheme, by the way, positive values of $\hat{y}$ correspond to increasingly confident correct classification, and negative values of $\hat{y}$ correspond to increasingly confident incorrect classification.)
As a concrete example, the hinge loss function is a mathematical formulation of the following preference:

Hinge loss preference: When evaluating planar boundaries that separate positive points from negative points, it is irrelevant how far away from the boundary the correctly classified points are. However, misclassified points incur a penalty that is directly proportional to how far they are on the wrong side of the boundary.

Formally, this preference falls out of the fact that a correctly classified point incurs zero loss once its planar distance $\hat{y}$ is greater than 1. On the other hand, it incurs a linear penalty directly proportional to the planar distance $\hat{y}$ as the classification becomes more badly incorrect.
Computing the loss value means computing the value of the loss for a particular set of training points and a particular boundary. Minimizing the loss means finding, for a particular set of training data, the boundary for which the loss value is minimal.
For a dataset as in the 2D picture provided, first draw any linear boundary; call one side the positive (or red square) side, and the other the negative (or blue circle) side.  You can compute the loss of the boundary by first measuring the planar distance values of each point; here, the signed distance between each training point and the boundary. Points on the positive side have positive $\hat{y}$ values and points on the negative side have negative values.  Next, each point contributes to the total loss: $L = \sum_i \ell(\hat{y}, y)$. Compute the loss for each of the points now that you've computed $\hat{y}$ for each point and you know $y=\pm 1$ whether the point is a red square or blue circle.  Add them all up to compute the overall loss.
The best boundary is the one that has the lowest loss on this dataset out of all possible linear boundaries you could draw. (Time permitting, I'll add illustrations for all of this.)
If the training data can be separated by a linear boundary,  then any boundary which does so will have a hinge loss of zero— the lowest achievable value.  Based on our preferences as expressed by hinge loss, all such boundaries tie for first place.
Only if the training data is not linearly separable will the best boundary have a nonzero (positive, worse) hinge loss. In that case, the hinge loss preference will prefer to choose the boundary so that whichever misclassified points are not too far on the wrong side.

Addendum: As you can see from the shape of the curves, the loss functions in your picture express the following scoring rubrics:

Zero-one loss  $[y\hat{y} < 0]$ : Being misclassified is uniformly bad— points on the wrong side of the boundary get the same size penalty regardless of how far on the wrong side they are.  Similarly, all points on the correct side of the boundary get no penalty and no special bonus, even if they're very far on the correct side.
Exponential loss $[\exp{(y\hat{y})}]$ : The more correct you are, the better. But once you're on the correct side of the boundary, it gets less and less important that you be far away from the boundary. On the other hand, the further you are on the wrong side of the boundary, the more exponentially urgent of a problem it is.
$\log_2(\cdots)$ : Same, qualitatively, as previous function.
Hinge loss $\max(0, 1-y\hat{y})$ : If you're correctly classified beyond the margin ($\hat{y}>1$) then it's irrelevant just how far on the correct side you are. On the other hand, if you're within the margin or on the incorrect side, you get a penalty directly proportional to how far you are on the wrong side.
Comment: @Peter Sure! Glad it's useful. I think contributions to math stack exchange are already licensed under creative commons share-alike with attribution required, so if you share what you use, just make sure you indicate the author and license your content under the same license. https://creativecommons.org/licenses/by-sa/3.0/ .
Comment: Where is the plot of the hinge loss with the penalty from?
Comment: @Peter I made it with Inkscape.
Comment: nice. can I use it? I need it for my own purpose :)
Answer: The hinge function is convex and the problem of its minimization can be cast as a quadratic program:
$\min \frac{1}{m}\sum t_i + ||w||^2 $
$\quad t_i \geq 1 - y_i(wx_i + b) , \forall i=1,\ldots,m$
$\quad t_i \geq 0 , \forall i=1,\ldots,m$
or in conic form
$\min \frac{1}{m}\sum t_i + z $
$\quad t_i \geq y_i(wx_i + b) , \forall i=1,\ldots,m$
$\quad t_i \geq 0 , \forall i=1,\ldots,m$
$ (2,z,w) \in Q_r^m$
where $Q_r$ is the rotated cone.
You can solve this problem either using a QP /SOCP solver, as MOSEK, or by some specialize algorithms that you can find in literature. Note that the minimum is not necessarily in zero, because of the interplay between the norm of $w$ and the blue side of the objective function.
In the second picture, every feasible solution is a line. An optimal one will balance the separation of the two classes, given by the blue term and the norm.
As for references, searching on Scholar Google  seems quite ok. But even following the references from Wikipedia it is already a first steps.
You can draw some inspiration from one of my recent blog post:
http://blog.mosek.com/2014/03/swissquant-math-challenge-on-lasso.html
it is a similar problem. Also, for more general concept on conic optimization and regression you can check the classical book of Boyd.
Comment: +1 for the clues, but what would help me most is a very simple example, which is what my question asked. There is plenty of material out there that provides vague directions
Comment: Which kind of example?
Comment: For example, using, the points I provided. What would the hinge loss be? What the graph of the hinge loss look like? How do you minimize it?  What about with points that are not separable?
Answer: Hinge loss $l(y, \hat{y})$ is defined to be $\max(0, 1- y\hat{y})$ where $y \in \{1, -1\}$.
We want to use $\hat{y}$ to estimate $y$.
Let's try to understand $y\hat{y}$.
If $y=1$, we would want $\hat{y}$ to be as positive as possible, in particular, if $\hat{y} \ge 1$, we are happy and the hinge loss would be evaluated to zero. If $y<1$, we would want to penalize our prediction.
On the other hand, if $y=-1$, we would want $\hat{y}$ to be as negative as possible, in particular, if $\hat{y} \le -1$, we are happy and the hinge loss would be evaluated to zero. If $y>-1$, we would want to penalize our prediction.
These two conditions can be combined compactly, if the model is doing well, we would want $y\hat{y} \ge 1$ and we want penalize our model otherwise.

The graph that you usually see in textbook is the plot of $\max(0, 1-z)$ where $z=y\hat{y}$, for higher values of $z$, the loss function is evaluated to be zero. On the horizontal axis of the graph, the more towards the right you are, the better is the performance of prediction, hence you are being penalized less. Hence, you can see that all the graphs of the loss function is a decreasing function.

As a function of $z$, the minimal value of $\max(0,1-z)$  would be $0$. However, that would require $y\hat{y} \ge 1$. It would be great if we can achieve it, but we might not do it all the time. because after all $z=y\hat{y}$ and $\hat{y}$ depends on the training data.
Now let's talk about why can't we always be correct. First there are noises and also, secondly, the data could be just not separable. For example, if you data consist of $(x=1, y=1), (x=1, y=-1)$, no matter what you assign prediction, $\hat{y} $ at point $x=1$, you are going to make some mistakes.
If we want to use a linear prediction function, for your $2$ dimensional example, it looks  $$\hat{y}(x) = b+w_1x_1 + w_2x_2 $$
Note that there are $3$ parameters to estimate and hence visualization could be difficult.
Now, let's work on your particular example, let's get the coordiante first.
The data for the negative class are:
$$(x=(1,4), y=-1), (x=(3,10), y=-1), (x=(4,8), y=-1), (x=(8,5), y=-1)$$
The data for the positive class are:
$$(x=(8,11), y=1), (x=(9,16), y=1), (x=(12,8), y=1), (x=(13,17), y=1)$$
With that the data set. The function that we want to minimize is
\begin{align}f(b,w_1,w_2) &= \frac18 \left[\max(0, 1+(b+w_1+4w_2)) +  \max(0, 1+(b+3w_1+10w_2))\right.\\&+
 \max(0, 1+(b+4w_1+8w_2)) +  \max(0, 1+(b+8w_1+5w_2))\\&+
\max(0, 1-(b+w_1+4w_2)) +  \max(0, 1-(b+3w_1+10w_2))\\&+
 \left.\max(0, 1-(b+4w_1+8w_2)) +  \max(0, 1-(b+8w_1+5w_2))\right]\\&+ w_1^2+w_2^2
\end{align}
This formulation can be rewritten as
$$\min  \frac18 \sum_{i=1}^8 t_i +w_1^2+w_2^2$$
subject to $$t_i \ge 1-y_i(b+w_1x_{i1}+w_2x_{i2}) \forall i \in \{ 1, \ldots, 8\}$$
$$t_i \ge 0 \forall i \in \{ 1, \ldots, 8\}$$
Now, we have even more variables. Fortuantely, it is a special type of problem known as quadratic programming of which its solver is widely available. And for the special problem of minimizing regularized the hinge loss, there is a special name to it known as support vector machine and most modern programming language has library to solve it.
Comment: nice example. could you add the missing right brackets of the formula $f(b, w_1, w_2)$?
Comment: thanks for the correction. =)

How do you minimize "hinge-loss"?


Logical equivalence implication between Kleene and Classical logic

Question: For any propositional assertions, $\phi$ and $\psi$, expressed using only the standard propositional logical connectives $\{\lnot,\land,\lor,\rightarrow,\iff\}$, if $\phi$ and $\psi$ are logically equivalent in Classical logic, are they necessarily logically equivalent in Kleene logic, and vice versa? That is, is it the case that $$\phi \equiv_C \psi \iff \phi \equiv_K \psi,$$ (where C=Classical and K=Kleene)?
Logical equivalence is taken to mean sameness of truth table. I've worked out one direction of the biconditional, which is that $$\phi \equiv_K \psi \rightarrow \phi \equiv_C \psi.$$ This is because the specified set of logical connectives are classical-truth preserving in Kleene logic. So, for any two propositional assertions, $\phi$ and $\psi$, if $\phi \equiv_K \psi$, then $\phi$ and $\psi$ have the same truth table, by definition of logical equivalence. They therefore agree on all classical rows of the truth table, by the classical-truth preserving property of the set of connectives. But this set of classical rows just is the truth table for $\phi$ and $\psi$ in Classical logic, and since these rows are the same, $\phi \equiv_C \psi$. Therefore, $\phi \equiv_K \psi \rightarrow \phi \equiv_C \psi.$
But I can't figure out how to prove the other direction. I can argue that if $\phi \equiv_C \psi$, then $\phi$ and $\psi$ will agree on all classical rows of their truth tables in Kleene logic. But, I don't know what to say about the remaining rows?
Comment: This one's right, I promise...
Answer: I assume you are talking about Kleene's three-valued logic of indeterminacy. If so , the equivalence you are trying to prove does not hold, because
classical logic proves the law of excluded middle $\phi \lor \lnot \phi$, but Kleene's logic does not: if $U$ is the undefined truth value, $U \lor \lnot U$ is $U$ not $\top$.
[This needs to be combined with the trick in David C. Ullrich's answer as discussed below.]
Comment: It's not clear to me that that answers the question. It's true that $\phi \lor \lnot \phi$ is not a tautology, ie does not always evaluate to $T$. But there are _no_ tautologies in Kleene logic! He specified that logical equivalence means the truth tables are the same - a counterexample must involve two formulas with the same classical truth table but different Kleene truth tables...
Comment: Thanks, Rob. But, I think David's correct here. The question is not whether a given propositional assertion has the same truth table in Classical as it does in Kleene logic, but rather whether if two assertions have the same truth table in Classical, will they necessarily have the same truth table in Kleene? (You're right about the logic I'm referring to. And thanks for the link!) @DavidC.Ullrich
Comment: Yes, you're right. I was forgetting that there is no way of writing $\top$ in Kleene's logic, so $\psi$ being provable isn't equivalent to the equivalence $\psi \equiv T$ being provable. David's trick of conjoining another propositional variable solves the problem: $P \land \psi \equiv P$ is provable iff $\psi$ is.
Answer: Counterexample: $\phi=P$, $\psi=P\land(Q\lor\lnot Q)$.