Não usar chaves "{ }" em IF no PHP pode gerar problemas?

Question: Geralmente para verificações que modificam apenas uma linha eu tenho evitado o uso de chaves, pois o PHP aceita esse método, porem raramente vejo códigos de outros programadores assim... Exemplos
Meu método
if($thumb->SaveInDB('imagens','img'))
    $ok = true;
else
    $ok = false;

Método normal
if($thumb->SaveInDB('imagens','img'))
{
    $ok = true;
}
else
{
    $ok = false;
}

Faz alguma diferença usar as chaves "{ }" nesses casos? existe a possibilidade do php retornar erro ou algo do tipo?
Comment: Dá na mesma. Eu utilizo chaves por questão de organização.
Comment: as respostas do @DiegoVieira, bfavaretto e gpupo se complementam bem... acredito que seria bom se alguém incluísse em sua resposta referencia as outras para deixar a resposta bem completa :D
Comment: relacionada: https://pt.stackoverflow.com/questions/162974/qual-a-diferen%C3%A7a-entre-os-usos-do-foreach-no-php
Answer: Na verdade o IF sem chaves só pode ser usado apenas na execução de um comando e quando for uma cadeia de comandos você utiliza as chaves para indicar que, no instante { até o termino } execute. Veja os exemplos abaixo.
A mesma lógia aplica-se à linguagens como PHP, Javascript, Typescript e C#.
Isto irá funcionar!
PHP
if($meuVar == true)
   echo 'verdadeiro';
else
   echo 'falso';

if($meuVar == true)
{
   echo "Sim";
   echo "
 É verdadeiro";
}
else
   echo "Não
 É verdadeiro";

Isto NÃO irá funcionar!
PHP
if($meuVar == true)
   echo 'Sim';
   echo '
 é Verdadeiro';
else
   echo 'Não';
   echo '
 é Verdadeiro';

Eu mesmo utilizo em meus códigos quando irei executar apenas um comando, esse método também funciona em outras linguagens tal como C#
Isso também vale para outros comandos, exemplos abaixo.
PHP
for($i == 0; $i < 10; $i++)
   echo $i;

while($i < 10)
   echo $i++;

foreach($items as $item)
   echo $item->meuCampo;

Vou deixar uma demo do for e o while em ação. DEMO
Comment: Então na verdade as `{ }` só servem para garantir que temos uma cadeia de execuções, em outras palavras não existe possibilidade de erros quando não existe uma cadeia... seria mais ou menos isso?
Comment: se o comando for utilizado de forma correta ele não irá mostrar erros, mas lembre-se, apenas na execução de um comando, no exemplo do @bfavaretto ele mostra que pode ocorrer erro de lógica.
Answer: Isso é um debate polêmico em diversas linguagens, não apenas PHP. Não existe uma resposta correta. Em última instância é uma questão de estilo e não irá gerar problemas se todos os cuidados necessários forem tomados.
Muita gente recomenda sempre usar as chaves para evitar problemas durante a manutenção do código. Se você omite as chaves e em outro momento alguém (até mesmo você) decide incluir uma segunda instrução no corpo do if ou do else, pode esquecer de adicionar as chaves, e gerar um erro de sintaxe:
if($foo == 1)
   echo 'aaaa';
   echo 'bbbb'; // erro de sintaxe
else
   echo 'cccc';

Ou, pior ainda, um erro de lógica que pode passar despercebido:
if($foo == 2)
   echo 'aaaa';
else
   echo 'bbbb';
   echo 'cccc'; // executa incondicionalmente!!!

Answer: Como todas as respostas disseram, você só pode usar UM comando depois de um if sem chaves
Mas, se você não gosta das chaves, tem outra opção:
if($algumacoisa) :
    echo 'foo';
    echo 'bar';
endif;

O mesmo pra while, for e foreach, só que o final é trocado pra o respectivo nome com "end" anteriormente.
Exemplo
Answer: Apesar de executar,(IF sem chaves só pode ser usado apenas na execução de um comando) você terá um problema de escrita e organização, por isso é recomendado que você siga o que foi decidido na PSR-2:
5.1. if, elseif, else

An if structure looks like the following. Note the placement of
  parentheses, spaces, and braces; and that else and elseif are on the
  same line as the closing brace from the earlier body.

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

The keyword elseif SHOULD be used instead of else if so that all
  control keywords look like single words.
Comment: Observação. Trocaria `o que foi decidido na PSR-2` por `a recomendação do PSR-2`
Answer: Quando você omitir as chaves você só vai tratar a próxima instrução como o corpo da condição:
if ($x) echo 'foo';
é o mesmo que

if ($x) {echo 'foo'; }
mas lembre-se que

if ($x)
   echo 'foo';
   echo 'bar';

imprime sempre "bar"
PHP trata tudo em {} como uma única expressão "agrupados".
O mesmo vale para as outras instruções de controle (foreach e assim por diante)
Answer: Colegas
no suporte ja deparei com erros devido as faltas de aspas no if
codigo.....
if(true)
    function x();
    function Y();

executa function y() como parte do código sem levar em consideração o if
esse erro num código não muito legível me fez gastar um dia e meio e provoca erros aleatórios difíceis de encontrar


Erro ASP.net MVC

Question: Tenho este código, a funcionar perfeitamente tal como quero
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <form class="well form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID_Reserva)

            @Html.LabelFor(model => model.ID_Cliente, "ID_Cliente", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("ID_Cliente", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ID_Cliente, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.DataEntrada, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.DataEntrada, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DataEntrada, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.DataSaida, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.DataSaida, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DataSaida, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.TipoQuarto, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.TipoQuarto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.TipoQuarto, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.NumeroQuarto, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.NumeroQuarto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NumeroQuarto, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.NumeroNoites, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.NumeroNoites, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NumeroNoites, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Preço, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Preço, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Preço, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Observaçoes, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Observaçoes, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Observaçoes, "", new { @class = "text-danger" })

                <input type="submit" value="Salvar" class="btn btn-default" />

    </form>

}

Contudo, quando tento mudar esse codigo em cima para este codigo,no sentido de mudar o formato ( motivo estético ) da-me o seguinte erro !
Codigo

    <form class="well form-horizontal" action=" " method="post" id="contact_form">

            Nome Cliente

                    <input name="Nome Cliente" class="form-control" value="@Model.Cliente.Nome">

            Data Entrada

                    <input name="Data Entrada" class="form-control" value="@Model.DataEntrada">

            Data Saída

                    <input name="Data Saída" class="form-control" value="@Model.DataSaida">

            Tipo Quarto

                    <input name="Tipo Quarto" class="form-control" value="@Model.TipoQuarto">

            NºQuarto

                    <input name="NºQuarto" class="form-control" value="@Model.NumeroQuarto">

            NºNoites

                    <input name="NºNoites" class="form-control" value="@Model.NumeroNoites">

            Preço

                    <input name="Preço" class="form-control" value="@Model.Preço">

            Observações

                    <textarea class="form-control" name="Observações" value="@Model.Observaçoes"></textarea>

    </form>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

            <button type="submit" class="btn btn-success">Editar</button>
            @Html.ActionLink("Ir para a listagem de Reservas", "Index")

}

Ao executar isto da-me este erro

Entidade
namespace WebApplication.Models.BaseDados
{
    using System;
    using System.Collections.Generic;

    public partial class Reserva
    {
        public int ID_Reserva { get; set; }
        public int ID_Cliente { get; set; }
        public System.DateTime DataEntrada { get; set; }
        public Nullable<System.DateTime> DataSaida { get; set; }
        public string TipoQuarto { get; set; }
        public int NumeroQuarto { get; set; }
        public Nullable<int> NumeroNoites { get; set; }
        public Nullable<decimal> Preço { get; set; }
        public string Observaçoes { get; set; }

        public virtual Cliente Cliente { get; set; }
    }
}

Answer: Quando é dado um post em uma action de um controle que recebe um objeto como parâmetro ele "pega" os dados através do name das propriedades. Provavelmente o erro ao salvar ocorre porque não está indo os valores preenchidos. Altere os names para o mesmo nome da propriedade, exemplo
Antes:
<input name="Tipo Quarto" class="form-control" value="@Model.TipoQuarto">

Depois:
<input name="TipoQuarto" class="form-control" value="@Model.TipoQuarto">

obs: Por que não usar o razor, sendo que os inputs estão iguais os gerados por ele?
Answer: Para ver os erros utilize o seguinte codigo  em  seu  savaChange
try
        {
             ... o restante do codigo
            db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                        ve.PropertyName,
                        eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
                        ve.ErrorMessage);
                }
            }
            throw;
        }

Assim  você conseguirar ver quais campos estão ocorrendo erro ao validar, o  seu  erro  não está no  cshtml e sim no  seu arquivo cs muitoprovavel dentro da entidade isso ocorre geralmente quando campos estão com valores null
coloque um breakpoint para ver o retorno nesse codigo que te passei
Comment: o mapeamento que o @MarcosBrinner quis dizer é se a propriedade TipoQuarto está configurada referente a [DataAnnotation](http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx) ou mapping [Fluent API](http://www.entityframeworktutorial.net/code-first/configure-entity-mappings-using-fluent-api.aspx).
Comment: Usei isso, mas nao me mostrou os erros ... eu penso que o erro tenha a ver com o ID_Reserva
Comment: vc debugou  na linha deste codigo, costuma não  imprimir  no console tive um erro  similar  a esse
Comment: seria melhor você postar o codigo de seu entity(entidade) ao invez do View
Comment: Eu fiz umas alteraçoes no codigo que me forneceu... agora ja diz o erro. Deu me isto ---> : 'The 'O campo TipoQuarto é necessário.' property does not exist or is not mapped for the type 'Reserva'.'
Comment: Certo, meio  caminho  andado mas  preciso que poste sua entity aqui para ver o campo, se  você estiver usando o fluent api, posta  o  mapping também
Comment: o erro fala que o campo TipoQuarto é necessario mas  não existe ou não está sendo mapeado no entity Reserva, ou seja ele está requisitando um valor que não existe, muito provavel o erro está no relacionamento das suas tabelas ou no  seu  mapeamento,  caso você tenha mapeado esse campo como requerido você tem  que fornece-lo na hora de salvar os dados no banco
Comment: Editei agora a questao e ja coloquei a entidade, o que tenho nela. Quanto ao maping nao percebi o que quer dizer , comecei estes dias em Mvc e ainda estou com dificuldades
Answer: Levando em conta que o erro foi estourado no db.SaveChanges() como System.Data.Entity.Validation.DbEntityValidationException, recomendo que você verifique o objeto passado no método de Edit (Reserva reserva). Mas olhando rapidamente o seu cshtml modificado e levando em conta que você está fazendo uma edição dos dados já inseridos, falta o Id para alteração.
Por exemplo em sua view antiga apresenta o hidden: @Html.HiddenFor(model => model.ID_Reserva), mas em sua nova view não identifiquei nenhum componente entregando o id para modificação.
OBS: Um modo rápido de "visualizar" este problema, seria colocar um breakpoint em seu método e verificar o parâmetro reserva para um melhor entendimento do objeto que está sendo alterado.
Comment: o erro dele é The 'O campo TipoQuarto é necessário.' property does not exist or is not mapped for the type 'Reserva'.'
Comment: acrescentei isto  mas deu o mesmo erro ...
Comment: @Heftysilva, teria como passar o que está vindo do parâmetro reserva? Que este exception gerado é claramente algo que vai contra o modelo implementado em seu código.
Comment: @DanielNicodemos da uma  lida nos comentarios da minha resposta ele conseguiu identificar o erro que está no TipoQuarto, talvez ajude a achar a solução
Comment: Então pode ser uma das situações: 1 - Pode estar mapeado como not null e estar sendo enviado nulo na edição. 2 - Não está mapeado ao modelo a propriedade TipoQuarto.
Comment: @MarcosBrinner, este erro ainda não foge da situação do objeto passado. Seria ótimo se ele publicasse o model `Reserva` e o que está sendo passado neste parâmetro também. Mas o caminho é este mesmo sinalizado, a validação mesmo do modelo ao que está sendo passado pelo parâmetro.
Comment: Já publiquei o Modelo Reserva,
Comment: @Heftysilva Verifique se na passagem do parâmetro `reserva` a propriedade `TipoQuarto` está sendo enviada como `null`
Comment: Nao estou a perceber como posso fazer isso, mas acredito que o problema é mesmo esse !
Comment: @Heftysilva, coloque um breakpoint no método e assim que você chamar este método de editar pressione `SHIFT` + `F9`. Vai aparecer a tela de QuickWatch. Nela você escreve o nome do parâmetro passado (no caso o parâmetro `reserva`) e pressione enter. Dentro deste adicionado, navegue pelas propriedades deste objeto (que no caso você irá pesquisar dentro do parâmetro `reserva` a propriedade `TipoQuarto`)
Comment: Desde já, obrigada pela ajuda!! Acabei de fazer isso e no TipoQuarto aparece como null

Erro ASP.net MVC


What are the things a vocalist or singer eat or drink to enhance voice

Question: I am a keyboardist and love to sing, but my voice is not up to my satisfaction. I have been wondering if there is any specific food, fruit, drinks or anything whatsoever that can improve  a vocalist or singer's voice.
I know fervently well that there are lots of voice enhancing exercises out there.
But what I am asking for is something you eat or drink that could instantaneously correct errors, fix breakages and clear your voice for smooth and hassle free singing.
Answer: In a word, no. Nothing but well oriented work will allow you to improve your voice (unless there is lack of hydration or some physiological problems to begin with, in which case proper hydration or some specific treatment may help).
A lot of things can harm it, though: lack of hydration,  smoking, heavy drinking, and extremely iced drinks. Some foods cause flegm (it varies from person to person) that just before singing can also become a nuisance.
Eating and drinking before going to bed (even just water) may cause gastric fluid to reach the throat and cause irritation of the vocal folds.
A visit to a specialized voice therapeut, preferably an M.D., will help identify potential physiological problems, if there are any that may be impeding your progress, and recomend care or remedial procedures, if required. Getting to know your instrument is good advice for any musician, vocalist is not an exception.
(thanks to Todd Wilcox for helping make this answer more useful).
Comment: As you allude to in your answer, one could make the case that there is one thing someone can drink to help their voice: water. I suppose that only helps if one is not getting enough of it already, but I would guess that most people could be better hydrated. Hydrating effectively definitely made a difference for my voice. It is true that water will not "instantly" help your voice, which was part of the question.
Comment: Todd, you're right, of course. Also, some specific physiological difficulties (excess flegm, harsh throat, etc.) could be helped by specific care, including ingestion of some substances, thus removing some obstacles for improvement.I'll edit my answer not to be so "radical".
Comment: @joseem Well I was thinking there could be something like that  . Anyways I will take note of the aforementioned. thanks
Answer: There is no magic bullet (or food or drink) that will suddenly transform you from an average singer to an Idol finalist.  However - what you eat or drink prior to singing can have an effect on your voice and should certainly be carefully considered.
The most important thing you can do (as mentioned by others) is to be sure your body is well hydrated. Your vocal apparatus consists of mucous membranes and other tissues that function best when fully hydrated.  If your body lacks proper hydration, all the tissues in your body are at greater risk of injury and may fail to function at their optimal level.
You can't hydrate just your throat and vocal folds by drinking a gallon of water right before you sing.  To obtain the optimal fluid balance in your vocal apparatus, you must achieve full body hydration on a cellular level in advance.  To do that - start drinking plenty of fluids at least two hours before you sing (or just make a healthy fluid intake level part of your daily routine).  Also prior to singing, you should avoid chemicals that dehydrate your body such as caffeine and alcohol and non essential over the counter medications that list dryness as a side effect.
When I have a performance coming up where I will be singing, I start planning at least a day ahead by drinking plenty of water and cutting back on coffee and avoiding alcohol the day before (and day of) a gig.  I'll wait until after the show to enjoy an adult beverage (as long as I am not performing the next day).
I try not to eat a big meal prior to singing. I don't want my energy and blood supply being diverted to digestion (or anything coming back up during my performance).
As mentioned by Joseem, you should avoid foods which might result in acid reflux.  I have had bad luck with the citric acid in fruit juice tightening up my throat. Extremely salty foods might tend to dry out your throat if eaten right before singing.  Have you ever seen what happens when you pour salt on a slug (don't try it)?  You do need salt in your body - but gradual and regular intake is the way to get the salt (just like water) into your system on cellular vs. topical level.
On stage I keep room temperature (not cold) water to keep my throat wet and maintain hydration. If I had a thermometer I might shoot for body temperature water.
I also keep a plastic jar of raw, organic, honey (not processed) and take a shot every now and then.  For whatever reason it seems to help me personally - but I can't cite any scientific studies that prove it's efficacy for singers. I have read of some science that confirms that raw honey is a natural anti inflammatory and anti oxidant.  And it seems to act as a temporary lubricant for my throat.
Some of my performing friends use products such as Singer's Saving Grace, Entertainer's Secret or Vocalzone Throat Pastilles.  I have not personally tried these and don't know if their perceived effectiveness is real or imagined.  I would hesitate to take the marketing hype on the websites as gospel. These products tout various ingredients as having lubricating and anti inflammatory properties.
The only thing I am absolutely positive that works from personal experience - and has plenty of science behind it is proper hydration. It's guaranteed to make a difference!  But you must start the process of full body hydration well in advance of your performance.  Good luck and have fun!
Comment: "start drinking plenty of fluids at least a day before you sing" is good advice, although as you note, since normally one would want to practice singing virtually every day, one should always maintain hydration to keep one's voice in good shape for daily singing practice. I've read (although without corraboration) that it can actually take a week to become fully hydrated. Other downsides to eating before singing include reduced space for diaghram expansion and the possibility of lingering food bits flying everywhere, even into one's lungs on the inhale.
Comment: @ToddWilcox  all good points!  I mentioned food coming back up during performance and that was meant to include exhaling it as well as all the other ways food can come back out the same way it went in which shares the vocal tract and is never good - no matter what causes it to come back up.  Proper hydration is indeed a process that occurs over an extended period - the main point being, you can't achieve it in a short period of time (like an hour or two prior to a gig).  Good point about the diaphragm.  That's probably the main reason not to eat a large meal prior to singing.
Comment: Hydration is not a process that occurs over an extended period. It does not happen instantaneously -- it takes a little time for your body to absorb the water; 30-60 minutes should be sufficient (unless you're coming to your gig from a lengthy desert hike). It does make sense to drink water *during* the gig, too!
I don't know of any evidence for honey. The science you mention is for the direct topical use of medical grade honey, but believe me, you do not want any honey sitting directly on your vocal cords!
I agree to avoid alcohol...but it can make you *think* you've improved your voice. ;)
Comment: @MysteriousWhisper you might be right about the day before.  I read that in a magazine article but further research points to two hours. I edited the answer - thanks for your help.  I sip water on stage because singing tends to dry out my mouth and throat inhaling all that air.  I am not the only singer who uses honey and It seems to work for me.  If you can link an article from a nutritionist or medical journal that indicates that honey is bad for your vocal chords I would love to see it and might reconsider.
Comment: Ah, to clarify, it's not bad to have honey. I only meant that it doesn't go *onto* your cords where it might have anti-inflammatory (and anti-breathing) effects; it goes into your esophagus. Lots of singers find it soothing; there's no problem with that!
Comment: @MysteriousWhisper Thanks.  It's very difficult to get anything in contact with your vocal cords.  I suppose you could gargle.  But honey is a little thick for gargling ;-)


How to register an onclick event so it knows the object it is called from?

Question: I have some simple HTML & Javascript code:
Hej

function Hello(el)
{
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e);
        }, false);
    }
}

var hello = new Hello;
hello.test(function()
{
    console.log(this);
});

I would like to use "this" in console.log() but I want it to refer to the instance of hello.
How should I change the definition of Hello?
Answer: You can use Function#call, which lets you bind this to whatever you want:
function Hello(el)
{
    var el = document.getElementById('test');
    var that = this;
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun.call(that, e);
        }, false);
    }
}

See this jsfiddle.
Comment: Thank you. I didn't know about this "call" method :)
Answer: In your this.test function replace:
fun(e);

With:
fun.call(that, e);

And add the following before your event listener:
var that = this;

Answer: You need to pass it to the passed function. The method addEventListener already provides you with access to the calling element through the usage of the this keyword in the specified listener function. So in order for this object to make it to your "fun" function, it needs to be passed as a variable.
function Hello(el)
{
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e, this);   // Adding the parameters to pass
        }, false);
    }
}

var hello = new Hello();
hello.test(function(event, el)  // The passed function should be ready to receive it
{
    alert(el.innerText);
});

I tested it with this fiddle.
Edit: Not sure I read the question fully the first time, but if you want to have access to Hello from within the function, you'll need to provide an instance of it from within your "class definition".
function Hello(el)
{
    var self = this;
    var el = document.getElementById('test');
    this.test = function(fun)
    {
        el.addEventListener('click', function(e)
        {
            fun(e, self);   // Adding the parameters to pass
        }, false);
    }

    this.someProperty = "to test the value";
}

var hello = new Hello();
hello.test(function(event, obj)  // The passed function should be ready to receive it
{
    alert(obj.someProperty);
});

I tested this second version with this fiddle update.


Why FancordionRunner suiteSetup is not being called?

Question: I am following MyFancordionRunner example from Fancordion v1.0.4 official documentation to test a BedSheet application, but the suiteSetup method (see below) is not being called and the server remains null, causing the fixture tests to fail with a NullPointerException.
override Void suiteSetup() {
    super.suiteSetup
    server = BedServer(AppModule#.pod).addModule(WebTestModule#).startup
}

Looking at FancordionRunner source code, the runFixture(Obj fixtureInstance) method should be invoking suiteSetup() the first time a Fixture is run as per this piece of code...
FixtureResult runFixture(Obj fixtureInstance) {
    ...
    locals := Locals.instance
    firstFixture := (locals.originalRunner == null)
    if (firstFixture) {
        locals.originalRunner = this
        suiteSetup()
        ...
}

But for some reason in my case the condition (locals.originalRunner == null) must be returning false, causing the suiteSetup() invocation to be skipped. It seems that this piece of code uses Fantom Actors which I'm not familiar with.
I am manually invoking the suiteSetup within MyFancordionRunner like this:
override Void fixtureSetup(Obj fixtureInstance) {
    if (server == null) suiteSetup
    ...

This workaround solves the NullPointerException issue and allows the fixtures to run successfully but I don't know if this workaround is defeating the purpose of the Actor logic, which I presume is meant to invoke suiteSetup only once.
Can anyone explain what could be going on here that is preventing the suiteSetup method from being called within runFixture(...), please?
Answer: I don't know what's going on here without seeing a lot more code.
The only part of Actor being used is Actor.locals() which is really just a pot to hold thread local variables - as it is assumed that all tests are run in the same thread.
As you shown, the logic in runFixture() is pretty simple, are you sure it is being called?


Block content returns no results for anonymus user only

Question: I've setup View Block that renders a custom content type. The issue is that block content shows up for logged users only. I ensured that anonymus user has "view published content" permission. No permission restrictions are set for that specific block.
any ideas what is wrong here? Could I use a Devel to inspect that somehow? thx!
Answer: There are multiple layers of permissions which might responsible for this,trying to cover some of them if that helps you.

Check right in the views configuration page and check "access" should be set to "view publish content".
Ensure you are not having contrib module like block_access or custom code which is putting a check the block view on user role basis.
Ensure if you are using contentaccess module or nodeaccess module and they are not letting the block visible to anonymous user.
Comment: You are the man! Nodeaccess was overriding view permission! Thanks a bunch you saved my day! :)
Comment: @Antonio glad it helped you :)


Azure Application Gateway - question about override backend path

Question: I've been working with the Azure Application Gateway for a while and I have some doubts about the Override Backednd Path option. I would appreciate if someone could clarify if my reasoning is correct.
Assumptions:

listener: mysite.mycompany.com
backend: myserver1.mycompany.com / myserver2.mycompany.com

HTTP Settings:

Override backend path: /images
Override with new hostname: Yes -> Pick hostname from backend target

Based on the settings above, if I send a request to mysite.mycompany.com, how will the App Gw forward it? My assumption would be that it will forward it to either myserver1.mycompany.com/images or myserver2.mycompany.com/images, but that does not seem to work properly.
Regards,
Wojtek
Comment: Hi Wojtek, Did you found any answers to your question?
Answer:
I send a request to mysite.mycompany.com, how will the App Gw forward it?
My assumption would be that it will forward it to either myserver1.mycompany.com/images or myserver2.mycompany.com/images, but that does not seem to work properly.

That's exactly how it works.


Getting syntax error for println in scala

Question: I'm trying to run the following code but getting an error on Scala 3.0.0:
// saved as file Upper1.scala

class Upper1:
  def convert(strings: Seq[String]): Seq[String] =
    strings.map((s: String) => s.toUpperCase)

val up = new Upper1()
val uppers = up.convert(List("Hello", "World!"))
println(uppers)

% scala Upper1.scala

-- [E080] Syntax Error: /Users/Deb/Desktop/Temp/Upper1.scala:7:0 ------------
7 |println(uppers)
  |^^^^^^^
  |Expected a toplevel definition
1 error found
Error: Errors encountered during compilation

Am I running it incorrectly?
Comment: is it clear why u cannot use `println` at the top level? Should I give u more details?
Comment: That would help a bit more to understand why we can't use it.
Answer: At the top-level, you can write only definition (e.g., val, def, class, ...) but not expression (e.g., 1 + 1, or in general functional call).
Therefore, if you wanna execute println(uppers) during the execution, you can write the main of the program:
@main
def main(): Unit =
  println(uppers)


Can a private MSMQ queue be renamed?

Question: Can you rename an existing private MSMQ queue on Windows Server 2003?
Comment: I was going to suggest editing the text file in the msmq\storage\lqs directory that contains the configuration for the private file.
After testing it, though, I found it didn't work.
Answer: I don't think you can, but you can always deleted and create a new private queue by the name you desire can you not?
Comment: Absolutely, I was just asking for the sake of a customer.  Renaming would mean you wouldn't have to reconfigure permissions and such.
Answer: No you can't rename a private queue.

Can a private MSMQ queue be renamed?


Logistic Regression Interaction Term

Question: I am trying to get my head around interaction terms. Suppose if I fit a model and try to predict pass or fail for state exams. The independent terms are: rank of school, results in midterm and over GPA score. Would I be right to say I believe that there could be a interaction term between rank of school and GPA score?  If what i am saying is true, how would I test that the new model with the interaction term was better than the old model?
Answer: To elaborate on @Michael Chernick's apt answer:
You might first fit a model with predictors A, B, and AxB. If the interaction term adds value, more likely than not that term will appear significant in the model.
Next, you can compare the 'full' (A, B, AxB) model versus a 'reduced' model including only A and B.  The model selection criteria @Michael Chernick recommends (AIC or alternatively, BIC) allows you to compare the fit of both models while correcting for the fact that models with more terms usually always fit better than models with fewer terms.
Answer: Analysis of deviance
Since the models you're interested in comparing are nested - your interaction model is a special case of your non-interacted model - you could also do an 'analysis of deviance' (like an analysis of variance, but suitable for generalized linear models such as logistic regression).  That would test whether it was worth putting the interaction term in.
Out of sample performance
If one of the two models you are comparing is not a special case of the other then you'll certainly need to look at model comparison statistics like AIC or BIC, or possibly to something like cross-validation.  These statistics (AIC and cross-validation at least) are trying to give you an idea of what you could expect from the model on new data.  If this is what counts as a 'good' in a model, then these are your statistics.
The cost of mistakes
Another, very general way to compare the two logistic regression models (nested or not) would be to compare the ROC curves for them.  That would be a measure of model fit under all possible assumptions about the relative cost of mistaking a passing student for a failing student versus the opposite.  Typically some models perform well when the costs skew one way and other when it skews the other.  A model whose ROC curve always dominates another is better under all loss structures.
There are, inevitably, some caveats to all these, but it's a start.
Answer: To choose the better model you would use a variable selection criterion such as AIC. The interaction term is plausible since the better (higher ranking) schools should make it more likely that a student will pass the state exam.
Comment: For an R example of using AIC in non-hierarchical models, have a look [here](http://stats.stackexchange.com/questions/116935/comparing-non-nested-models-with-aic). The next question you will probably have is how to draw inference from the interaction terms. For that you can see [here](http://www.ats.ucla.edu/stat/stata/seminars/interaction_sem/interaction_sem.htm) and [here](http://www.theanalysisfactor.com/interpreting-interactions-in-regression/)

Logistic Regression Interaction Term


iBatis query failing in spite of it working in an Oracle SQL editor

Question: The following query is working perfectly fine in an SQL Editor (Oracle), but failing through iBatis.
INSERT INTO TEST_TABLE (COL1, COL2, COL3, COL4, COL5 )
    SELECT   #col1#,
                #col2#,
                #col3#,
                #col4#,
                #col5#
                FROM DUAL
        where not exists (select 1 from TEST_TABLE where COL1 = #col1#)

Exception - ORA-00933 - SQL Command not properly ended.
Comment: Where are using such a complex query? you can use MERGE for this.
Comment: Honestly speaking I did not know of MERGE statement.  I will read about it and try applying in this case.  Thanks @Ivan
Answer: I found the issue.  iBatis somehow needs parenthesis to identify sub queries.  I could resolve the issue by adding brackets around the outer SELECT clause.
INSERT INTO TEST_TABLE (COL1, COL2, COL3, COL4, COL5 )
    ( SELECT   #col1#,
                #col2#,
                #col3#,
                #col4#,
                #col5#
                FROM DUAL
        where not exists (select 1 from TEST_TABLE where COL1 = #col1#))


Is there a way to get the pathname of Chrome's default download folder using the Chrome Extensions API?

Question: The closest thing I've seen is chrome.downloads.showDefaultFolder(), but that opens up a file dialog. Is there a way to get the folder pathname as a string?
Answer: No, there is no convenient way to get the "physical" location of the downloads directory through the Chrome extension API.
In theory, you could enable access to local URLs (at chrome://extensions/), download a file, then search through the directories on the disk via XHR and/or content scripts for the target directory. This is not practical though. First because it is extremely inefficient, and secondly because normal users will not allow your extension to access their disk.
Comment: Yeah, I figured the capability might not exist in the API. The workaround does seem too hackish to use, but it's good to know it exists. For stackoverflow questions like this, should I accept the "no" answer, or leave it open?
Comment: @iqnivek An authorative no is also an (acceptable) answer, until someone else passes by and says "XXX is now possible, here's how: ...". In that case you can simply accept the new answer.


Is there a model of KP with no $\emptyset'$ ordinal notation for the Bachmann-Howard ordinal?

Question: The Bachmann-Howard ordinal (BHO) is a large recursive ordinal defined using ordinal collapsing functions. Kripke-Platek set theory (KP) is a fragment of ZF obtained by removing powerset, swapping replacement and separation with collection and separation both restricted to formulae with only bounded quantifiers. The program of ordinal analysis reveals that the proof-theoretic ordinal of KP is the BHO, i.e. the BHO is a sharp upper bound on the order types of recursive ordinal notations that KP proves well-founded. (A good exposition of ordinal analysis is Rathjen's "The Realm of Ordinal Analysis".)
Since KP cannot prove "$\prec$ is well-founded" for any recursive well-ordering $\prec$ of $\mathbb N$ with order type BHO (specifically there is no index $e$ of a computable well-ordering of order type BHO such that KP can prove "$\{e\}$ well-orders $\mathbb N$"), there must be a model of KP which thinks there is no computable well-ordering with order type BHO. However, does the same result happen when looking at $\emptyset'$ well-orderings with order type BHO?
I am not sure how to apply any kind of compactness result to construct such a model, or if there is a generalization of ordinal analysis about $\emptyset'$ ordinal notations instead of computable ones.
Comment: In fact, KP proves that every ${\bf 0'}$-computable well-order has a computable copy. Spector's theorem is overkill for this; the simpler argument in Ash/Knight goes through much more clearly in $\mathsf{KP}$.
Comment: Thank you! I think this would fit as an answer.
Comment: 'Tis done (and I've added some more info).
Answer: In fact, $\mathsf{KP}$ proves that every ${\bf 0'}$-computably-presentable well-order has a computable copy. The classical result along these lines is of course Spector's theorem, that every hyperarithmetic well-order has a computable copy. I believe that Spector's theorem goes through in $\mathsf{KP}$ - in particular, I think the argument for a more general result goes through in $\mathsf{KP}$ - but checking this takes a bit of care. Fortunately, we don't need Spector here: there's a much simpler result in Ash/Knight's book Computable structures and the hyperarithmetic hierarchy that for any ${\bf 0'}$-computably-presentable linear order $L$ the linear order $\omega\cdot L$ (= "replace each point in $L$ by a copy of $\omega$") has a computable copy. This is their Theorem 9.8; unfortunately, the proof is an exercise for the reader, but it's a simple finite-injury priority argument and goes through without difficulty in $\mathsf{KP}$.


Counting the number of polynomials of degree $n$ with integer coefficients.

Question: I was working through Understanding Analysis by Abbott and one of the problems asked to prove that the set of all algebraic numbers is countable. We know a number $x \in \mathbb{R}$ is algebraic if there exist integers $a_0, \dots , a_n \in \mathbb{Z}$, not all 0, such that
$$
a_nx^n+a_{n-1}x^{n-1}+ \cdots + a_1x + a_0 = 0.
$$
So, for $n \in \mathbb{N}$, if we let $A_n$ be the set of algebraic numbers obtained as roots of polynomials with integer coefficients that have degree $n$ we can write this set as a union of finite sets as follows. For each $m \in \mathbb{N}$ consider the set
$$
B_m=\left\{x : \sum_{i=0}^n{a_ix^i}=0, \sum_{i=0}^n{|a_i|}=m, |a_n| \geq 1 \right\}.
$$
Since each polynomial has a finite number of roots, if we can show that the number of polynomials satisfying the constraints in the set $B_m$ is finite then we know that $B_m$ itself is finite. With $B_m$ being finite we then have $A_n = \cup_{m=1}^\infty{B_m}$. We show that $B_m$ is finite as follows.
The set up of the problem is that we are given a polynomial of degree $n$
$$
a_nx^n+a_{n-1}x^{n-1} + \cdots + a_1x+a_0
$$
where $a_n, \dots, a_0 \in \mathbb{Z}$, and we want to count the total number of polynomials such that
$$
|a_n|+|a_{n-1}|+ \cdots + |a_1|+|a_0|=m.
$$
Since it's specified that our polynomial is of degree $n$, we know that all of our polynomials will contain an $n$th degree term in them, and so $|a_n| \geq 1$. To make things easy for us we will separately count the polynomials that have just 1 term in them, then 2 terms, then 3 terms, all the way up to $n+1$ terms. Before proceeding with this we take a quick detour. We will prove the following lemma.

For $n \in \mathbb{N}$, given $b_1,b_2, \dots , b_n, m \in \mathbb{N}$ and $m \geq 2$, the sum $b_1+ \cdots + b_n = m$ can be formed in ${m-1}\choose{n-1}$ ways.

We prove this via induction. The case when $n=2$ is immediately obvious. If we know $b_1,b_2 \geq 1$ and $b_1+b_2=m$ then $b_1$ can take on any integer value from 1 to $m-1$ and in doing so this determines the value of $b_2$. Thus there are $m-1$ = ${m-1}\choose{1}$ arrangements of this sum. Now assume the statement holds true for $n=k-1$. Thus for any $b_1,b_2, \dots , b_{k-1}, m \in \mathbb{N}$ with $m \geq 2$,  $b_1+\cdots+b_{k-1}=m$ can be formed in ${m-1}\choose{k-2}$ different ways. We show it holds true for $n=k$.
Let $b_1,b_2, \dots , b_k, m \in \mathbb{N}$ and $m \geq 2$. If we fix $b_1=1$ our sum becomes $b_2+b_3+\cdots+b_k=m-1$, and we know that there are ${m-2}\choose{k-2}$ possible ways to form this sum via the inductive step. Similarly, if we fix $b_1=2$ our sum becomes $b_2+b_3+\cdots+b_k=m-3$ and again via the inductive step we know that there are ${m-3}\choose{k-2}$ possible ways to form this sum. Continuing this process we find that the total amount of ways to form this sum is
$$
{{m-2}\choose{k-2}}+{{m-3}\choose{k-2}}+ \cdots + {{m-(m-(k-2))}\choose{k-2}}.
$$
And now since we know that if $0 \leq k \leq n$ then $\sum_{j=0}^n{j \choose k} = {{n+1}\choose{k+1}}$, this sum becomes
$$
{{m-2}\choose{k-2}}+{{m-3}\choose{k-2}}+ \cdots + {{k-2}\choose{k-2}}={{m-1}\choose{k-1}}
$$
and our result follows via induction. Note that if $n > m$, the total number of ways the sum can be formed is 0 and the formula still holds.
Back to counting our polynomials. If the polynomial has $k$ terms where $1 \leq k \leq n+1$ we begin by choosing $k-1$ of the coefficients that will be included in our polynomial (because we know $a_n$ must be included), there are ${{n}\choose{k-1}}$ possible choices for the other coefficients aside from $a_n$. The absolute values of these coefficients must also sum up to $m$, and by our lemma above there are ${{m-1}\choose{k-1}}$ possible ways to make this sum. Lastly, since we are working with absolute values the sign of each coefficient can flip between positive and negative and so there are $2^k$ possibilities for choice of signs for all the coefficients. Thus there are
$$
{{n}\choose{k-1}}{{m-1}\choose{k-1}}2^k
$$
total polynomials of degree $n$ with $k$ terms who have integer coefficients that sum to $m$ in absolute value. Using this we have that the total number of polynomials of degree $n$ who have integer coefficients that sum to $m$ in absolute value is given by
$$
{{n}\choose{0}}{{m-1}\choose{0}}2^1+{{n}\choose{1}}{{m-1}\choose{1}}2^2+\cdots+{{n}\choose{k-1}}{{m-1}\choose{k-1}}2^k+\cdots+{{n}\choose{n}}{{m-1}\choose{n}}2^{n+1}.
$$
Since this is a finite number of polynomials, and each polynomial has a finite number of roots then each $B_m$ is a finite set and as stated before $A_n = \cup_{m=1}^\infty{B_m}$ is a countable union of finite sets and is thus countable. The algebraic numbers can then be represented as the countable union of countable sets $\cup_{n=1}^\infty{A_n}$, which is itself countable. So the algebraic numbers are countable.
Is this a valid proof? It seems like there should be an easier way to prove the lemma compared to the way that I did. Is there an intuition behind why the total possible ways to make that sum is ${m-1}\choose{n-1}$? Any comments and corrections are welcome as well!
Answer: Your proof looks correct! To make a more simple proof I would define $B_m = \{x : \sum_{i = 0}^n a_ix^i = 0$ where $m = max \{|a_i|\}\}$.
I think this proof is a little easier since its a little easier to show that the number of polynomials satisfying the constraints in the set $B_m$ is finite. Let $j \in \mathbb{Z}$ be maximal such that $|a_j| = m$. Clearly $a_j = -m$ or $a_j = m$ so there are $2$ choices for $a_j$. Next there are $n + 1$ many possible choices for $j$. Now each of the $n - j$ terms before $j$ must in the set $\{-m + 1, -m+ 2, ... , -1, 0, 1,... , m - 2, m - 1\}$ i.e. there are $2m - 1$ many choices for each term of the $n - j$ terms preceding $a_j$. Similarly there are $2m + 1$ many choices for each term of the $j$ terms following $a_j$.
Finlay we see that the number of polynomials satisfying the constraints for $B_m =$ the number of choices for $j$ times the number of chooses for each term of the $n - j$ terms before $a_j$ times the $2$ choices for the value of $a_j$ times the number of choices for for the $j$ terms after $j$
$= n + 1 \times (2m - 1)^{n - j} \times 2 \times (2m + 1)^j$
After this the rest of the proof is the same as yours.
Comment: That's another great way! I like this a lot better, thank you.


Calculating Probability of a Classification Model Prediction

Question: I have a classification task. The training data has 50 different labels. The customer wants to differentiate the low probability predictions, meaning that, I have to classify some test data as Unclassified / Other depending on the probability (certainty?) of the model.
When I test my code, the prediction result is a numpy array (I'm using different models, this is one is pre-trained BertTransformer). The prediction array doesn't contain probabilities such as in Keras predict_proba() method. These are numbers generated by prediction method of pretrained BertTransformer model.
[[-1.7862008  -0.7037363   0.09885322  1.5318055   2.1137428  -0.2216074
   0.18905772 -0.32575375  1.0748093  -0.06001111  0.01083148  0.47495762
   0.27160102  0.13852511 -0.68440574  0.6773654  -2.2712054  -0.2864312
  -0.8428862  -2.1132915  -1.0157436  -1.0340284  -0.35126117 -1.0333195
   9.149789   -0.21288703  0.11455813 -0.32903734  0.10503325 -0.3004114
  -1.3854568  -0.01692022 -0.4388664  -0.42163098 -0.09182278 -0.28269592
  -0.33082992 -1.147654   -0.6703184   0.33038092 -0.50087476  1.1643585
   0.96983343  1.3400391   1.0692116  -0.7623776  -0.6083422  -0.91371405
   0.10002492]]

I'm using numpy.argmax() to identify the correct label. The prediction works just fine. However, since these are not probabilities, I cannot compare the best result with a threshold value.
My question is, how can I define a threshold (say, 0.6), and then compare the probability of the argmax() element of the BertTransformer prediction array so that I can classify the prediction as "Other" if the probability is less than the threshold value?
Edit 1:
We are using 2 different models. One is Keras, and the other is BertTransformer. We have no problem in Keras since it gives the probabilities so I'm skipping Keras model.
The Bert model is pretrained. Here is how it is generated:
def model(self, data):
        number_of_categories = len(data['encoded_categories'].unique())
        model = BertForSequenceClassification.from_pretrained(
            "dbmdz/bert-base-turkish-128k-uncased",
            num_labels=number_of_categories,
            output_attentions=False,
            output_hidden_states=False,
        )

        # model.cuda()

        return model

The output given above is the result of model.predict() method. We compare both models, Bert is slightly ahead, therefore we know that the prediction works just fine. However, we are not sure what those numbers signify or represent.
Here is the Bert documentation.
Comment: Are you actually asking if it is *possible*, or if it is a valid/good idea? If the former, how can such a simple numeric manipulation *not* be possible? You may find the last part of own answer in [Tensorflow & Keras prediction threshold](https://stackoverflow.com/questions/62396675/tensorflow-keras-prediction-threshold) helpful.
Comment: @desertnaut Thanks. The example you provided is about Keras. I have two models: One is Keras and the other is Bert. I'm already using the same approach (predmax < threshold) in order to identify the "Unclassified" predictions in Keras model. However, as you can see in the example above, the Bert prediction output is not probabilities. There are negative and positive numbers and their sum is not 1.
Comment: This is not apparent from your question - please edit & update accordingly to clarify such crucial details; how exactly these numbers are produced would be also necessary. If you do not have probability outputs, how can we talk about any threshold?
Comment: @desertnaut Edited. That's what I'm trying to ask, actually. I don't know what these numbers represent, maybe they're a different kind of probability. Then, the question might turn back into "is it possible" rather than "valid/good idea".
Comment: What I meant is - what exactly is your `BertTransformer` model? Are you sure it is used for classification? Please post at least some link to its documentation or something.
Comment: @desertnaut I edited the question, and added model and documentation. Hope this will be helpful.
Answer: BertForSequenceClassification returns logits, i.e., the classification scores before normalization. You can normalize the scores by calling F.softmax(output, dim=-1) where torch.nn.functional was imported as F.
With thousands of labels, the normalization can be costly and you do not need it when you are only interested in argmax. This is probably why the models return the raw scores only.


Get directions in map in swift 3

Question: I wanna get directions from my own location to pre-defined location. I can do it by opening it in browser but it needs to be done in application only. Is there a way to draw route and update it as current location changes?
I am using following code which opens in browser. I want it to remain in the application only
let url = URL(string: "http://maps.apple.com/?saddr=\(lat),\(long)&daddr=\(latgest),\(longgest)&dirflg=d")!

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
else
{
UIApplication.shared.openURL(url)
}

Answer: Let's say the place you are is the "source" and you want to go to your "destination". Try this:
import MapKit
import UIKit

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapview: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    mapview.delegate = self

    let request = MKDirectionsRequest()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.203314, longitude: -8.410257), addressDictionary: nil))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.112808, longitude: -8.498689), addressDictionary: nil))
    request.requestsAlternateRoutes = false
    request.transportType = .walking

    let directions = MKDirections(request: request)

    directions.calculate { [unowned self] response, error in
        guard let unwrappedResponse = response else { return }

        for route in unwrappedResponse.routes {
            self.mapview.add(route.polyline)
            self.mapview.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let polylineRenderer = MKPolylineRenderer(overlay: overlay)
        polylineRenderer.strokeColor = UIColor.blue
        polylineRenderer.fillColor = UIColor.red
        polylineRenderer.lineWidth = 2
        return polylineRenderer

    }

}

Don't forget to Outlet the mapview.
This worked for me.
Let us know if it worked for you as well.
Answer: The embedded map framework you are looking for is called MapKit and it supports routing.  There are many tutorials for it, such as https://www.raywenderlich.com/110054/routing-mapkit-core-location
Comment: Thanks for reply but this shows me poly line, i want direction in real time tracking like if current location moves forward to that address it shows turn this way and give direction .

Get directions in map in swift 3


HTML Resizing Text

Question: I want to have a div stay at 500 height.  Text is dynamically inserted into this div.  Different text lengths are inserted.  Right now, my div expands to accomodate the full text.  How can I instead have text shrink so it always fits within the bounds?
Comment: Unless there is a small range of text lengths, I would suggest you stay away from shrinking the text.  It won't take long for it to become small and illegible.  Better to hide the text and then show it on hover or something similar.
Comment: Do you have an example or some code you already have?
Comment: By shrinking, do you mean making the font smaller or cutting some characters from the string?
Comment: Instead of shrinking the text, will a scroll-bar suffice?
Answer: You cannot use HTML and CSS to dynamically re-size text. You can set the div height to 500px, and either have scroll or hide any extra text.
You can use JavaScript to re-size the text dynamically, but the solution may not be practical if the text length varies widely. Your text will be unreadable if under 10px.
Comment: I could continue to expand the div, but the real problem is I have absolute positioned items in the expandable div, and when it shrinks too small, my absolute items move outside of the container.  Is there a way to have absolute items within a relative container better adjust themselves when the container expands/shrinks?
Comment: @spentiak, can you show us en example. Post it on http://jsfiddle.net/ if you can.

HTML Resizing Text


Mapear classe com json.net

Question: Existe alguma maneira de mapear o nome das propriedades de uma classe sem utilizar a annotation JsonProperty do Json.NET?
A seguinte estrutura mostra duas classes que herdam da classe Bar. Contudo, o nome json da propriedade da classe pai (Bar) deveria ser diferente na serialização das duas classes filhas.
public class Bar
{
    [JsonProperty("property_1")]
    public string Property1 {get; set;}
}

public class Foo : Bar
{
    [JsonProperty("property_2")]
    public string Property2 {get;set;}
}

public class FooBar : Bar
{
    [JsonProperty("property_3")]
    public string Property3 {get;set;}
}

Além disso, gostaria de evitar colocar annotations nas entidades de domínio da aplicação, realizando o mapeamento para json em um projeto a parte.
Comment: Já tentou tornar a `Property1` como `virtual` e mudar a anotação com overload da propriedade?
Answer: Vinicius, como alternativa, você pode utilizar o Attributo [DataContract]e [DataMember] no lugar do [JsonObject] e [JsonProperty] respectivamente.
Mas ao faze-lo, terá de colocar [DataMember] em todas as propriedades que deseja serializar, uma vez que omitir o [DataMember] será o mesmo de adicionar um [JsonIgnore].
Esta abordagem pode ser bastante util, se quiser expor os seus objetos através de uma WebAPI ou WCF, inclusive o [DataMember] possui o atributo EmitDefaultValue, caso setado para false, ele não irá serializar propriedades enquanto estiverem com o valor default.
Mas se que saber se tem como declarar o nome da propriedade de uma forma que não utilize Attributes, infelizmente você terá de escrever o seu proprio JsonConverter, então talvez não seja viavel.
se preferir, pode adicionar os atributos em outras classe, para faze-lo utilize o Attributo [MetadataType], isto abordagem é especialmente util para manter atributos em classes geradas de forma automatica, então vamos pegar como base a seguinte classe:
public partial class MyClass
{
    public string Property1 {get; set;}
    public string Property2 {get; set;}
    public string Property3 {get; set;}
}

então teriamos de fazer o seguinte em um arquivo separado:
[MetadataType(typeof(MyMetaData))]
public partial class MyClass
{

}

public class MyMetaData
{
    [DataMember(Name = "property_1")]
    public string Property1 {get; set;}

    [DataMember(Name = "property_2")]
    public string Property2 {get; set;}

    [DataMember(Name = "property_3")]
    public string Property3 {get; set;}
}

apesar de acreditar que a resposta acima não tenha resolvido o seu problema, espero ter lhe dado um norte.
Comment: tentei utilizar o JsonConverter mas ao chamar uma biblioteca externa (NEST) que também usa o Json.NET, ele ignorou o converter. Estou testando com DataContract e DataMember, dando override nas propriedades que preciso mudar o nome. Não é o que eu desejava, porque estou usando DDD e queria passar esta configuração pra camada de infraestrutura, e não na de domínio, mas deve servir no momento

Mapear classe com json.net


Add animation (slower, smoother change) on Bokeh chart data changes

Question: Is there a way (built-in or quick workaround) to make bokeh charts' data change more smoothly? I am streaming some data in a Bokeh dashboard, the data changes drastically from time to time, and I would like to allow a few seconds for the chart data to update (imagine a bar chart), like an animation ...
How can I achieve this? Any hint would be useful.
P.S. I am using Bokeh server and am already customizing my template (html, css, js)
Answer: There are two ways to animate things with Bokeh right now:

Animate manually by changing the data slightly at short intervals. Pro: pretty easy to implement. Con: a lot of data churning, especially given that you're using a server
Create custom glyphs that support such animation. Pros and cons are the opposite. You can check out this example to get an idea of how it might be done
Comment: Cool, it seems a lot of work to do per case. That'd be a good feature to add in order to help Bokeh stand out visually compared to visualization JS libraries.


Largest Interval Length for $1/3$ Translation Trick

Question: On the Wikipedia page for dyadic cubes, the article claims that if $\Delta^{\alpha}$ denotes all the dyadic cubes in $\mathbb{R}^{n}$ translated by a vector $\alpha\in\mathbb{R}^{n}$, then

There is a universal constant $C>0$ such that for any ball with radius $r<1/3$, there is an $\alpha\in\left\{0,1/3\right\}^{n}$ and a cube $Q$ in $\Delta^{\alpha}$ containing $B$ whose diameter is no more than $Cr$.

This seems false. In one dimension, consider the interval $I=[-\epsilon/2,1/3+\epsilon/2]$ for $1\gg\epsilon>0$. For $\epsilon>0$ sufficiently small, any such interval $J$ must have $\left|J\right|=2^{l}\geq 1/2$. The only dyadic intervals and $1/3$-translate dyadic intervals which intersect and $I$ and satisfy $\left|I\right|\geq 1/2$ are of the form $[0,2^{l}), [-2^{l},0)$ and $[1/3,2^{l}+1/3), [-2^{l}+1/3,1/3)$, none of which contain $I$.
In fact, playing around with the $\epsilon$, it seems that for any length strictly greater than $1/3$, we can find an interval $I$ which is not contained in a cube in $\Delta^{\alpha}$ for $\alpha\in\left\{0,1/3\right\}$.
If $\left|I\right|\leq 1/3$ (i.e. $r\leq 1/6$), then I believe the claim above is true. Let $l\in\mathbb{Z}$ be such that
$$2^{l}\in\begin{cases}(4\left|I\right|,8\left|I\right|], & {\left|I\right|\leq1/8} \\ [1], & {1/8<\left|I\right|\leq 1/3}\end{cases}$$
Suppose that $I$ is not contained in any dyadic interval of generation $l$. Then there exists an endpoint $x=2^{l}p$ of a dyadic interval $J$ which belongs to the interior of $I$. Since $\bigcup_{m\in\mathbb{Z}}[m+1/3,m+1+1/3)=\mathbb{R}$ and $2^{l}\leq 1$, it follows that there is a $J^{*}\in\Delta^{1/3}$ such that $x\in J^{*}$. If $y=q2^{l}+1/3$ is an endpoint of $J^{*}$, then
$$\displaystyle\left|x-y\right|=2^{l}\left|\dfrac{2^{-l}}{3}+q-p\right|\geq\dfrac{2^{l}}{3}\displaystyle\begin{cases}= 1/3, & {1/8<\left|I\right|\leq 1/3} \\ >\left|I\right|, & {\left|I\right|\leq 1/8}\end{cases}$$
since $q-p$ is an integer, $-l\geq 0$, and $2^{-l}/3$ is never an integer. Since $\left|x-z\right|<1/3$, for any endpoint $z$ of $I$, it follows that $I\subset J^{*}$.
I don't think any of this really matters, though, for application of this "trick". For example with maximal operators, it is enough by scaling and monotone convergence to consider supremums over all balls or cubes of diameter $\leq R$, for some choice of $R>0$.
Answer: You are quite right. The author must have thought of diameter when writing "radius".
Indeed, $0$ is not an interior point of any dyadic interval, and $1/3$ is not an interior point of any $1/3$-translated dyadic interval. So it's necessary to rule out the intervals containing both $0$ and $1/3$ as interior points.
You are also right in that the precise number does not matter. The way I see it, what one really needs is the existence of $\gamma<1$ such that for any $k\ge 0$, the family of intervals
$$\mathcal F_k = \{ 2^{-k}[n,n+1] : n\in\mathbb{Z}\}\cup \{1/3+ 2^{-k}[n,n+1] : n\in\mathbb{Z}\}$$
forms a "$\gamma$-padded cover"   of the line, meaning that   $\bigcup_{Q\in \mathcal F_k } \gamma Q =  \mathbb{R}$.
(For negative $k$, i.e., larger cubes, one naturally needs to translate by larger amounts.)
Comment: Thanks for chiming in. Sometimes one--as least I--see something that seems so clearly wrong that if nobody's corrected it, I must be wrong.


Can address space be recycled for multiple calls to MapViewOfFileEx without chance of failure?

Question: Consider a complex, memory hungry, multi threaded application running within a 32bit address space on windows XP.
Certain operations require n large buffers of fixed size, where only one buffer needs to be accessed at a time.
The application uses a pattern where some address space the size of one buffer is reserved early and is used to contain the currently needed buffer.
This follows the sequence:
(initial run) VirtualAlloc -> VirtualFree -> MapViewOfFileEx
(buffer changes) UnMapViewOfFile -> MapViewOfFileEx
Here the pointer to the buffer location is provided by the call to VirtualAlloc and then that same location is used on each call to MapViewOfFileEx.
The problem is that windows does not (as far as I know) provide any handshake type operation for passing the memory space between the different users.
Therefore there is a small opportunity (at each -> in my above sequence) where the memory is not locked and another thread can jump in and perform an allocation within the buffer.
The next call to MapViewOfFileEx is broken and the system can no longer guarantee that there will be a big enough space in the address space for a buffer.
Obviously refactoring to use smaller buffers reduces the rate of failures to reallocate space.
Some use of HeapLock has had some success but this still has issues - something still manages to steal some memory from within the address space.
(We tried Calling GetProcessHeaps then using HeapLock to lock all of the heaps)
What I'd like to know is there anyway to lock a specific block of address space that is compatible with MapViewOfFileEx?
Edit: I should add that ultimately this code lives in a library that gets called by an application outside of my control
Comment: And why do you call VirtualFree before MapViewOfFileEx?
Comment: Is there some reason you do not use a mutex for the whole memory block or a list of mutexs for predefined address spaces within that initially allocated memory?
Comment: Ah I think I understand. You want to optimize MapViewOfFileEx behind its back by guaranteeing the same heap block is always free.
Comment: Sebastian: yes - where optimize actually means guarantee success in environment where contiguous address space is unlikely to last out in the open
Comment: Noctis:how would that help? - I can't mutex every allocation made by any code in the process
Comment: So you're saying you UnMapViewOfFile() then try to map again at the same address?
Comment: Oh stupid Microsoft. They have all the necessary interface for implementing it, but don't have the implementation...
Answer: You could brute force it; suspend every thread in the process that isn't the one performing the mapping, Unmap/Remap, unsuspend the suspended threads. It ain't elegant, but it's the only way I can think of off-hand to provide the kind of mutual exclusion you need.
Comment: Enumerate all threads: http://msdn.microsoft.com/en-us/library/ms686780(VS.85).aspx

Since there's a race (a thread could spawn another thread after you take the snapshot but before you suspend it) you will need to repeat the process until each snapshot identifies no further threads.

From the snapshot (which gives you thread IDs) you can OpenThread each thread to get a handle, and then call SuspendThread on that handle.
Comment: I appreciate the suggestion but I worry this is a hack for hack replacement - I've realised the original problem is also open to VirtualAllocEx calls from another process.  I believe the API is not going to help me out.
Comment: I meant to add that, yes, you could get memory allocated by another process. But this is an uncommon event, to say the least. I suppose the real point is: there's no way within the API to do this (at least, not that I know of), so just how hard do you want to try to prevent it? The mechanism I suggested will at least stop the common case (a thread within the process performing an allocation that uses the block you need), which strikes me as "good enough", but your needs may differ.
Comment: I understand - my hope had been that I had overlooked a rigorous solution - it'll take some more thought to decid the best way forward
Answer: Have you looked at creating your own private heap via HeapCreate? You could set the heap to your desired buffer size. The only remaining problem is then how to get MapViewOfFileto use your private heap instead of the default heap.
I'd assume that MapViewOfFile internally calls GetProcessHeap to get the default heap and then it requests a contiguous block of memory. You can surround the call to MapViewOfFile with a detour, i.e., you rewire the GetProcessHeap call by overwriting the method in memory effectively inserting a jump to your own code which can return your private heap.
Microsoft has published the Detour Library that I'm not directly familiar with however. I know that detouring is surprisingly common. Security software, virus scanners etc all use such frameworks. It's not pretty, but may work:
HANDLE g_hndPrivateHeap;

HANDLE WINAPI GetProcessHeapImpl() {
    return g_hndPrivateHeap;
}

struct SDetourGetProcessHeap { // object for exception safety
   SDetourGetProcessHeap() {
       // put detour in place
   }

   ~SDetourGetProcessHeap() {
       // remove detour again
   }
};

void MapFile() {
    g_hndPrivateHeap = HeapCreate( ... );

    {
        SDetourGetProcessHeap d;
        MapViewOfFile(...);
    }
}

These may also help:
How to replace WinAPI functions calls in the MS VC++ project with my own implementation (name and parameters set are the same)?
How can I hook Windows functions in C/C++?
http://research.microsoft.com/pubs/68568/huntusenixnt99.pdf
Comment: What i would like is to reserve (but not commit) the address space in the same manner as VirtualAlloc can but to then safely hand it over to MapViewOfFileEx
Comment: OK, you don't actually need the performance benefit of having an in-memory buffer, you only want to guarantee the memory is available.
Comment: I see where you're coming from - but this may well be a leap too far -> I'm guessing I hadn't overlooked anything obvious:)
Answer: Imagine if I came to you with a piece of code like this:
void *foo;

foo = malloc(n);
if (foo)
   free(foo);
foo = malloc(n);

Then I came to you and said, help!  foo does not have the same address on the second allocation!
I'd be crazy, right?
It seems to me like you've already demonstrated clear knowledge of why this doesn't work.  There's a reason that the documention for any API that takes an explicit address to map into lets you know that the address is just a suggestion, and it can't be guaranteed.  This also goes for mmap() on POSIX.
I would suggest you write the program in such a way that a change in address doesn't matter.  That is, don't store too many pointers to quantities inside the buffer, or if you do, patch them up after reallocation. Similar to the way you'd treat a buffer that you were going to pass into realloc().
Even the documentation for MapViewOfFileEx() explicitly suggests this:

While it is possible to specify an address that is safe now (not used by the operating system), there is no guarantee that the address will remain safe over time. Therefore, it is better to let the operating system choose the address. In this case, you would not store pointers in the memory mapped file, you would store offsets from the base of the file mapping so that the mapping can be used at any address.

Update from your comments
In that case, I suppose you could:

Not map into contiguous blocks.  Perhaps you could map in chunks and write some intermediate function to decide which to read from/write to?
Try porting to 64 bit.
Comment: Unfortunately the value of the pointer is not the problem - the problem is guaranteeing a large enough hole in the  address space.  Easy at startup hard later on.
Comment: I'd also add I'm supporting a mature system rather than designing a new one.
Comment: Unfortunately 32bit support will be required for a while yet - I agree the refactor is a possibility (I hinted at it in my question) - I was hoping this question might discover an alternative - thanks for the second opinion, much appreciated.
Comment: -1 for the malloc analogy. malloc is much higher level interface. On the system level the address space and the physical memory are separate. WinAPI gives you the ability to *reserve* an address space and then *allocate* (commit) a physical memory that is addressed by this region. MapViewOfFileEx was intended to allow exactly this, unfortunately it looks like the employee that started implementing it was fired before she finished, leaving us with yet another completely useless function...
Comment: @ybungalobill - "On the system level the address space and the physical memory are separate" -- when did I suggest otherwise?  I think you should chill out and re-read what I say, because the analogy holds. Expecting to reserve a chunk of address space and resize it without moving is extremely silly because something unrelated going on in your process might end up using the virtual address you end up requesting later. Especially re-read my quote from MSDN. This approach is asking for pain. To use another analogy to `malloc`, it's like using `realloc(p, n)` and assuming it always returns `p`.
Comment: @asveikau: neither me nor the OP want to resize the reserved region, we want just to remap the view to another view of the same size. [So how does the analogy holds exactly](http://c2.com/cgi/wiki?ArgumentByAnalogy)? A better analogy would be a placement `new` in C++: `T* newAddr = new(addr) T; assert(newAddr == addr);` And yes, I read the MSDN page even before I came here, what it effectively says is that the `MapViewOfFileEx` is useless.
Comment: @ybungalobill OK, but I parse what you are saying as essentially the same thing.  Or at least, the principal reason you can't do it is the same.  You can't rely on what unrelated things in your process are doing that might conflict with you.
Comment: @ybungalobill Also, it's not the API's fault if you're using it to do something stupid.  Let's say you're the implementation of `MapViewOfFileEx` and you're modifying page tables, but the caller's address range includes an entry that is already in use.  What do you do?  The obvious answer is to fail the call.  From that perspective the answer to this question is self evident.
Comment: @ybungalobill Lastly, as I re-read what was written, the `malloc` analogy holds.  `UnMapViewOfFile` effectively tells the system to release the page table entries, making it analogous to `free`.  Therefore any other caller can now reclaim that address space before your next call to `MapViewOfFileEx`.  The placement `new` analogy does not hold because there is never anything releasing the buffer in the middle.
Comment: @asveikau you seem to be helpfully explaining why it can't be done with the current API but maybe slightly missing what was being asked.  I think the placement new analogy is in the right direction.  I was hoping for an API that allowed MapViewOfFileEx to be called again for the same address and length without UnMapViewOfFile ever telling the system it was OK to take the address space back.
Comment: @morechilli Sorry to make you witness to all the flaming.  I don't think it's possible to do what you are asking.
Comment: @asveikau I came to the same conclusion unfortunately, all help and discussion much appreciated.
Answer: As the earlier post suggests, you can suspend every thread in the process while you change the memory mappings.  You can use SuspendThread()/ResumeThread() for that.  This has the disadvantage that your code has to know about all the other threads and hold thread handles for them.
An alternative is to use the Windows debug API to suspend all threads.  If a process has a debugger attached, then every time the process faults, Windows will suspend all of the process's threads until the debugger handles the fault and resumes the process.
Also see this question which is very similar, but phrased differently:
Replacing memory mappings atomically on Windows
Comment: Thanks for the cross link and suggestions.  Thankfully we have finally been allowed by our customer to phase out 32 bit support (for new work) so our address restrictions are less important - but the missing API functionality still frustrates me and remains a legacy issue.


The file '/SFPageService/6665FFF2-6B04-481C-B4E5-1339DA707C2D_39_Basic.aspx' does not exist

Question: We're having a problem with a Sitefinity 4.x deployment on Windows Server 2008 R2.
When we browse to the site we get a 404 error not found, even if we direct the browser directly to the /home file.
We've made sure that the app_data folder has the correct permissions.
We don't know what else could be wrong. It works perfectly on our internal staging environment though.
Any help would be greatly appreciated.
Answer: We managed to resolve this issue by removing the precompile option in Asp.net.


Referenced Entity as an Exposed Filter

Question: I have 2 Content Types: Activity and Event.
For each of Event node, there will be an Entity Reference field which References Activity Node.
Example:
Event:

Title: Hiking in Utah
Activity: Hiking (Entity reference field referencing Activity node hiking)

I am Referencing Activity In an Entity Reference Field in Event Content type...
How can we use "Referenced Entity" within Views and make them available as Exposed Filters ?
In the end I want the Referenced Entities to be visible in a Dropdown field and filter results on selection.
I've had a look at EVA, but i am unable to understand if that can be used to accomplish this.
Answer: You have to actually go into your entity reference field settings on your content type and enable the following:
Render Views filters as select list.
Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.
This will then allow your exposed filter in views to be rendered as a select list.
Comment: that worked perfectly, however i will be having more than 100 nodes in some content types which i will be referencing via Entity Reference. In that case can i keep using this structure as it is advised not to be used when there are over 100 entities ?
Comment: My understanding (as I recall reading some notes from the maintainer in a thread somewhere) is that this feature is pretty hacky. Therefore you are going to see a performance issue using it past 100 nodes. You are better off just using the textfeild by default.
Comment: actually i intended to use Taxonomy to relate contents. Say each content type would have a taxonomy, however i got that there are taxonomies for each content type, which didn't seem useful to me and i had to create Taxonomy each time a node was created (or automate this in some way). Entity ref, appeared to resolve this issue. Any better suggestion ? Also, im unable to undersand "textfield" that you have mentioned. Or should i stick to using Taxonomy, itself.
I need to be able to use them as Filters as well as for displaying "related" content in views blocks.
Comment: I would use taxonomy and use the inline entity reference module in conjunction with the term ref field. This way you can create new terms on the node add/edit page. However, I don;t know the entire ins and outs of what you are trying to do so it is really not a definitive answer, only a recommendation.
Comment: thanks for the answer, time and suggestion. Ill go with Taxonomy route at the moment, without any complexity as im not getting it :)
Comment: Hi @Nigel i need your opinion on the same query again.
I dropped the idea of using Entity Reference as it has the Limit of 100 nodes in Views Select.

However, i found that References Sub Module (Node references) does this with Ease. Whats your opinion on this, any bottlenecks that you see ? if i continue with Node References
Comment: I have only used it once in d7 as I tend to use entity reference in conjunction with inline entity form. It served me well but I don't see a real difference between the two. Also entity ref is included in d8 core. So there's an upgrade path.
Comment: I am dot that , but expose filter not show !!!
Answer: There is a better way to handle this using the Views Reference Filter Module
Create your view and reference it in your view in a field.

This module provides the views filter for entity ID or entity reference fields:

node ID
user ID
taxonomy term ID
term reference field (Drupal core)
entity reference field (Entity reference module)
Comment: Ah, this is the way to go! Thank you!

For others, remember to save the reference view you create, it won't show up on the drop down until the view is saved.
Answer: You can do this natively with Views. Add a relatinoship on the entity field, and a field as a filter and set it to use the relationship.

Referenced Entity as an Exposed Filter


A network related error or instance-specific error occured while establishing a connection to sql server

Question: This is the error which arises when I tried to debug an application under Visual C# 2010
I write that code to retrieve some rows from a database table, I already attached the two well known databases Pubs and Northwind to the db explorer, but the error remains
class Author
{
    SqlConnection _pubConnection;
    string _connString;

    public Author()
    {
        _connString = "Data Source=./INSTANCE2;Initial Catalog=pubs;Integrated Security=True";
        _pubConnection = new SqlConnection();
        _pubConnection.ConnectionString = _connString;
    }

    public int CountAuthors()
    {
        try
        {
            SqlCommand pubCommand = new SqlCommand();
            pubCommand.Connection = _pubConnection;
            pubCommand.CommandText = "Select Count(au_id) from authors";
            _pubConnection.Open();
            return (int)pubCommand.ExecuteScalar();
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            if (_pubConnection != null)
            {
                _pubConnection.Close();
            }
        }
    }
}

static void Main(string[] args)
{
   try
   {
      Author author = new Author();
      Console.WriteLine(author.CountAuthors());
      Console.ReadLine();
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
      Console.ReadLine();
   }
}

Answer: the Connection string isn't ok , i correct it and it works fine


What do they mean by 'This amp has a lot of headroom'?

Question: Do they mean how loud it will go without getting distortion?
Comment: gah. You edited it before I posted my answer :-)
Answer: I'd further qualify what ledfloyd has said: headroom defines the level you can obtain before the signal starts "clipping", that is: before the peaks begin to flatten out and resemble a square wave (the sound of which we call OD/distortion).
Once your signal's clipping, not only does it distort, it compresses somewhat as well (due to the fact that you get less room between the peak level and the average level - hence the name). Once you run out of headroom, you start to lose dynamics as well.
Comment: Good clarification and expansion :)
Answer: "Headroom" refers to how loud you can turn up an amp (usually a referring to a non-Master Volume Tube amp) before it starts to break-up into Distortion/Overdrive.


Armazenar dados da requisição app.post nodejs

Question: Fala galera, gostaria de saber como posso utilizar os dados recebidos da pagina para utilizar fora do app.post?

var SerialPort = require('serialport');
var Readline = SerialPort.parsers.Readline;
var methodOverride = require('method-override');

//faz requerimento dos modulos
var serveStatic = require('serve-static');
const express = require('express');
const socketIo = require('socket.io');
const http = require('http');
var path = require('path');

//cria servidor
const app = express();
const server = http.createServer(app);
const io = socketIo.listen(server);

//starta servidor na porta 3000
server.listen(3000, () => {
 console.log('Servidor Online na porta 3000');
});

//define um diretorio commo public para acesso as propriedades
app.use(serveStatic(path.join(__dirname, 'public'), {
 maxAge: '1d'
 }));

// retorna index quano recebe requição
app.get('/', (req, res, next) => {
 res.sendFile(__dirname + '/index.html');
 app.use(serveStatic(path.join(__dirname, 'public'), {
  maxAge: '1d'
  }));
});

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.route('/signup');
app.post( '/signup', urlencodedParser, function(req, res) {
 var portCOM = req.body.portCOM;
 var bauRATE = req.body.bauRATE;
 res.json(
  {
      message: 'signup success',
   portCOM : portCOM,
   bauRATE : bauRATE,
  }
 );
});

app.get(function(req,res){
 res.json({message: 'get request from signup'});
});

// configurações da comunicação serial
port = new SerialPort(portCOM, {
 baudRate: 9600,
    dataBits: 8,
    paridade: 'nenhum' ,
    stopBits: 1,
    flowControl: false ,
    parser: new SerialPort.parsers.Readline('\r')
});

//define um limite para acionar um evento
const ByteLength = require('@serialport/parser-byte-length');
const parser = port.pipe(new ByteLength({length: 4}));

//EXIBE OS LOG NO TERMINAL, INFORMAÇOES VINDA DO ARDUINO
port.open(function()
{
 console.log('Porta aberta');
});

var ModbusTCP = "";
parser.on('data', function (data)
{
  ModbusTCP = data.toString();
  ModbusTCP = ModbusTCP.replace(/(\r\n|\n|\r)/gm,"");
  var infLeng = ModbusTCP.length;

  console.log('tamanho do envio:',infLeng);
  console.log('Valor Hexadeciaml: ' + ModbusTCP);
});
Comment: Não basta apenas chamar uma função passando o req? Ou talvez o que você queira seja capturar e tratar esses argumentos antes de chegar no app.post com um middleware? Pode descrever o que você está tentando fazer?
Comment: estou passando alguns parâmetros do lado do cliente para conectar a uma porta serial, então preciso pegar estes parâmetros que estão armazenados dentro do app.post e trata-los fora do app.post
Comment: quando tento utilizar a variavel portCOM fora do app.post tenho o retorno portCOM is not defined.
Comment: Ainda não estou entendendo qual é a dificuldade. Não basta enviar `portCOM` ou `res` como parâmetro para outra função? Você pode editar a sua pergunta, postando o código completo, incluindo a parte que dá erro?
Comment: postei o código completo, na parte que configuro a conexão com a porta COM eu não consigo utilizar a variável.
Answer: Ao que dá para perceber, portCOM é utilizado em SerialPort, mas SerialPort não está sendo chamado através de um middleware, ele está direto na raiz do script, o que significa que ele será executado apenas uma vez quando o servidor for iniciado, antes mesmo do usuário enviar o valor de portCOM.
Para executar SerialPort apenas quando a reaquisição for enviada para a rota signup, você precisa colocar ou chamar o código dentro da função de callback da rota:
app.post('/signup', urlencodedParser, function (req, res) {
    const portCOM = req.body.portCOM;
    const bauRATE = req.body.bauRATE;

    criarPorta(portCOM);

    res.json({
        message: 'signup success',
        portCOM: portCOM,
        bauRATE: bauRATE,
    });
});

function criarPorta(portCOM) {
    port = new SerialPort(portCOM, {
        baudRate: 9600,
        dataBits: 8,
        paridade: 'nenhum',
        stopBits: 1,
        flowControl: false,
        parser: new SerialPort.parsers.Readline('\r')
    });

    // .
    // .
    // .
    // Restante do código
}

Ou então usar o código como middleware:
app.post('/signup', urlencodedParser, criarPorta, function (req, res) {
    const portCOM = req.body.portCOM;
    const bauRATE = req.body.bauRATE;

    res.json({
        message: 'signup success',
        portCOM: portCOM,
        bauRATE: bauRATE,
    });
});

function criarPorta(req, res, next) {
    const portCOM = req.body.portCOM;

    port = new SerialPort(portCOM, {
        baudRate: 9600,
        dataBits: 8,
        paridade: 'nenhum',
        stopBits: 1,
        flowControl: false,
        parser: new SerialPort.parsers.Readline('\r')
    });

    // .
    // .
    // .
    // Restante do código

    next();
}

Comment: showww muito obrigado, eu tinha feito diferente, havia colocado dentro do  middleware principal app.post e funcionou, mas o teu método é o correto e mais estável.
Comment: A estabilidade é a mesma, só é um pouco mais organizado. Vou dar uma dica que eu acabei não deixando na resposta: você pode usar o middleware `urlencodedParser` antes da declaração das rotas, dessa forma você não precisa declara-lo manualmente em todas as rotas que você criar. Apenas coloque `app.use(urlencodedParser)` acima da declaração das rotas, e o parse do corpo das requisições será feito da mesma forma.


Functional Analysis: countable Product of Compact Subsets of Metric Spaces is compact

Question: I'm revising for Functional Analysis exam and I'm trying to solve this problem. The part a) is clear for me but I have problem with b) and c) and hope someone can give me a hint how to start/solve it.
I think that in part c) the theorem of Tychonoff plays a role. But here we have compact SUBSET of $X_n$, so I'm not sure if it's even allowed or how I must argue that I can use the theorem.
For b) I don't have an idea at all. If someone could give me hint how to start that would be great.
The problem:
Let $(X_n,d_n)$,$n \in \mathbb N$, be a family of metric spaces and X the product space $X=\prod_n X_n$. Define $d: X \times X \rightarrow \mathbb R^+$ for $x=(x_n)_{n\in N}, y=(y_n)_{n\in N} \in X$ as follows:
$\sum_{n \in I} \frac{1}{2^n} \frac{d_n(x_n,y_n)}{1+d_n(x_n,y_n)}$.
Prove:
a) d is a metric on X. --> I have already done this.
b) Any open neighborhood $U \subset X$ of an arbitrary point $x \in X$ contains a neighborhood of thr form $\prod_{1\le n\le N} U_n(x_n) \times \prod_{n \gt N} X_n$, where $N \in \mathbb N$ and for each $1\le n\le N,U_n(x_n)$ denotes an open neighborhood of $x_n in X_n$.
c) If for any $n \in \mathbb N, K_n \subset X_n$ is compact, then $\prod_{n \in N} K_n$ is a compact subset of X.
Answer: As you are dealing with metric spaces you may instead concentrate on sequential compactness. For this it suffices to take any sequence $(\xi_k)_{k\geq 1}$ in the product $K=\prod_n K_n$ and use the socalled 'diagonal' trick to extract a subsequence that converges in $K$.
Comment: Okay, I will try it. But is it sufficient to argue with sequential compactness? I know sequentially compact metric space is compact.  But is it also true the other way around?
Comment: Yes, for metric spaces there is equivalence (see e.g. S Lang, Real and functional analysis, thm 3.8, but it should appear in most textbooks). The diagonal trick is the same as in Ascoli (if you know this?) and it is pretty much equivalent to your statement.
Comment: Yea, I think you mean the Cantor's Diagonal Argument, right? I think I've had it in Analysis. Thanks for the hint. Do you might also have a hint for part b?
Comment: For b) your nghd must contain an $r>0$ ball around $x$. Then you may  pick $n_0$ so that $2^{-n_0} < r/4$ and pick ngbhs in the first $n_0$ coordinates which have diameters smaller than $r/2$ in total. Then the ball of radius $r$ contains their product times anything in the remaining coordinates. Don't know if that is sufficiently clear?
Comment: I tried to draw it understand your intention. But I got stuck. Why picking smaller r/4 resp. r/2 arbitrarily? It just had to be smaller than the ball radius? And how does one choose n_0? Could you explain me why one could do it like this? I mean the idea behind this proof.
Comment: Suppose $B(x,r)\subset U$ for some $r>0$. As $2^{-n}$ goes to zero there is $N$ large enough so that $2^{-N}N$ you pick simply $X_n$ and note that for the metric $d$ their diameter does not contribute more than $\sum_{n>N} 2^{-n} = 2^{-N}<r/3$ so summing up we see that this gives a ngbhd of the wanted type containing $x$ and of diameter not greater than $2r/3$ thus sitting inside $B(x,r)\subset U$.


How to add watermark to the video part of this huge ffmpeg command that adds intro and outro with crossfade?

Question: I wrote a command that crossfade merge an intro, an outro, with a video:

ffmpeg -i intro.mp4 -i video.mp4 -i outro.mp4 -filter_complex "
[0:v]trim=start=0:end=9,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[intro];
[0:v]trim=start=9:end=10,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[firstfadeoutclip];
[1:v]trim=start=0:end=1,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[firstfadeinclip];
[1:v]trim=start=1:end=24,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[video];
[1:v]trim=start=24:end=25,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[secondfadeoutclip];
[2:v]trim=start=0:end=1,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[secondfadeinclip];
[2:v]trim=start=1:end=10,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[outro];
[firstfadeoutclip]format=pix_fmts=yuva420p, fade=t=out:st=0:d=1:alpha=1[firstfadeoutalpha];
[firstfadeinclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[firstfadeinalpha];
[secondfadeoutclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[secondfadeoutalpha];
[secondfadeinclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[secondfadeinalpha];
[firstfadeoutalpha]fifo[firstfadeoutfifo];
[firstfadeinalpha]fifo[firstfadeinfifo];
[secondfadeoutalpha]fifo[secondfadeoutfifo];
[secondfadeinalpha]fifo[secondfadeoinfifo];
[firstfadeoutfifo][firstfadeinfifo]overlay[firstcrossfade];
[secondfadeoutfifo][secondfadeoinfifo]overlay[secondcrossfade];
[intro][firstcrossfade][video][secondcrossfade][outro]concat=n=5[output];
[0:a][1:a] acrossfade=d=1 [audio]"
-vcodec libx264 -map "[output]" -map "[audio]" "output.mp4"

This huge command works fine.
But now what I want to do is to add a watermark to the video part:
[1:v]trim=start=1:end=24,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[video];

And I want to do it by merging this command (watermark) into that one above:
ffmpeg -i "1080p.mp4" -filter_complex "
movie=logo-wm.png[watermark];
[watermark][0:V]scale2ref=(1917*iw/1920)/3.5:(322*iw/1920)/3.5[wm][v];
[v][logo]overlay=main_w-overlay_w-20:20" "output.mp4"

The whole (1917*iw/1920)/3.5:(322*iw/1920)/3.5 scales the watermark proportionally using the scale2ref= filter. The 1917 is the width of my watermark image, and 322 is the height
It is overlayed in the top right corner with main_w-overlay_w-20:20
But I can't make it work I tried to add it by copying the parameters to the filter of [1:v] input. And by adding another input for the watermark that if I'm right it would be [3:v] instead of using the movie= filter. But I can't.
I know that I could do it in two steps, but I would like to do it at once, in just one command.
May anyone help me to merge them ? Thank you in advance !
Answer: Use
ffmpeg -i intro.mp4 -i video.mp4 -i outro.mp4 -i watermark.png -filter_complex "
[0:v]trim=start=0:end=9,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[intro];
[0:v]trim=start=9:end=10,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[firstfadeoutclip];
[3:v][1:v]scale2ref=(1917*iw/1920)/3.5:(322*iw/1920)/3.5[wm][v1ol];
[v1ol]trim=0:25[v1];[v1][wm]overlay=W-w-20:20,split=3[1va][1vb][1vc];
[1va]trim=start=0:end=1,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[firstfadeinclip];
[1vb]trim=start=1:end=24,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[video];
[1vc]trim=start=24:end=25,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[secondfadeoutclip];
[2:v]trim=start=0:end=1,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[secondfadeinclip];
[2:v]trim=start=1:end=10,setpts=PTS-STARTPTS,scale=480x360,setsar=sar=16/9[outro];
[firstfadeoutclip]format=pix_fmts=yuva420p, fade=t=out:st=0:d=1:alpha=1[firstfadeoutalpha];
[firstfadeinclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[firstfadeinalpha];
[secondfadeoutclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[secondfadeoutalpha];
[secondfadeinclip]format=pix_fmts=yuva420p, fade=t=in:st=0:d=1:alpha=1[secondfadeinalpha];
[firstfadeoutalpha]fifo[firstfadeoutfifo];
[firstfadeinalpha]fifo[firstfadeinfifo];
[secondfadeoutalpha]fifo[secondfadeoutfifo];
[secondfadeinalpha]fifo[secondfadeoinfifo];
[firstfadeoutfifo][firstfadeinfifo]overlay[firstcrossfade];
[secondfadeoutfifo][secondfadeoinfifo]overlay[secondcrossfade];
[intro][firstcrossfade][video][secondcrossfade][outro]concat=n=5[output];
[0:a][1:a] acrossfade=d=1 [audio]"
-vcodec libx264 -map "[output]" -map "[audio]" "output.mp4"

(I haven't checked the rest of your command, but maybe you meant to use setdar=16/9)
Comment: The command works but the watermark disappears after 1 or 2 seconds... Looks like if the trim duration wasn't properly applied. I used setsar because in the docs i've read that it also set the dar. If I used setsar in all the streams shouldn't I use the same in the stream for the watermark ?
Comment: I think the watermark is only applied to the `[firstfadeinclip]` but not to `[video]` and [`secondfadeoutclip`] I'm trying...
Comment: Corrected. Generated streams need to be duplicated for reuse, unlike source streams.


how can I disable a checkbox in a mustache view if a condition is met?

Question: this is part of the json response
"name_with_grade": "2º - A",
"rates": [
{
  "name": "Evaluación",
  "quantity": 1,
  "due_date": null,
  "optional": false,
  "rate": 300
},

and the mustache
      {{#rates}}
        {{#rate}}

            <input type="checkbox">
            {{name}}
            {{rate}}

        {{/rate}}
      {{/rates}}

rate could be blank hence the {{#rate}} but some are optional and i would like to disable the checkbox for those that aren't.
Answer: Changed the logic to be required instead of optional and this seems to do it, some better ideas welcome.

  <input type="checkbox"
    {{#required}}
      disabled="disabled" checked="checked"
    {{/required}}>

Comment: You could also use an inverted section... `{{^optional}} disabled="disabled" checked="checked"{{/optional}}`
Answer: You can add a class in order to enable/disable the controls based on a condition:

add an hidden field that will contain the condition (loaded in the server
side):
input type="hidden" runat="server" id="js_hfDisabled" value=""
add a class into the control:
input type="checkbox" class="js_disabled"
add a new function: into the $(document).ready(function()...
function enabled_disabled() {
        var jshfDis = $('#js_hfDisabled').val();
        $('.js_disabled').prop('disabled', jshfDis);
    }
and call it inside the $(document).ready(function()...