Need to wrap a Blender 2.49 game (Using Python 2.6.2) to C++ for Steam (Using Steamworks)

Question: how are you?
My name is Alejandro Navarro, game developer.
I reached Steam Greenlight while ago with a Blender 2.49 game, called ARKADIANAX
(I wanted to post the link, but I need more reputation to do that)
The thing is I know nothing about coding (There is a friend helping me with this, but he couldn't help me with this part either).
Blender 2.49 uses Python 2.6.2, and the Steam API (Steamworks) Uses C++, so I need to wrap the code. I tried a lot using this wrapper:
https://github.com/Gramps/SteamworksForPython
But I can't make this work. I'm getting errors:
Python script error from controller "cont5#CONTR#2" (Those are the names of the logic bricks which are calling the steamworks.py script)
Traceback (most recent call last):
  File "steamworks.py", line 4, in
    from ctypes import
The complete error is in the link I'm uploading to Mediafire together with Steamworks and Wrapper:
http://www.mediafire.com/download/h1097ag8kawg07m/Files.rar
I would be so grateful if anyone can give me a hand, I will add him to the credits of the game and I'll hang a painting of him in my house haha.
Thanks a lot for your time to read this.
Best wishes.
Comment: Do you know how old blender 2.49 is? it has now been 7 years since it was released. How much work would it be to update your game to use blender 2.77? Is it mostly logic bricks or is there a lot of python code? The age of blender 2.49 will leave you with limited help.
Answer: While blender 2.49 uses python, it only uses the python interpreter and includes a limited subset of standard python modules, which doesn't include ctypes. You can look through the blender install to find a zip file containing the python install used - this is part of the windows install (and optionally a linux build), inside this zip file you will find the python standard modules that are included. You should be able to get a corresponding python ctypes module and add it to this, it looks like you may also need to add the sys module as well.
If you don't have any luck with that approach, you could consider getting a copy of the source code and compiling your own version of blender. When you checkout the current source code as described at developer.blender.org you still have the ability to checkout the 2.49 source code and build a new copy of blender 2.49 with any c/c++ modifications you add. Using blender's code for examples you can add a c/c++ module that can be accessed through blender's python interpreter and compile it into blender's binary.


How does sw-toolbox router rule order/priority work?

Question: In my service worker (which uses sw-toolbox library) I have setup two routes as follows:
toolbox.router.any("/user/*", toolbox.networkOnly);
toolbox.router.any("/user/logout", toolbox.logoutHandler);

I assumed that the second rule which is specific to the "/user/logout" path, would act as an exception to the first rule (which is a blanket rule for the path "/user/*") however, I can confirm that it does not.
Am I using this sw-toolbox route config correctly?
Answer: I think the rules are independent, first matching rule wins. So this should works:
toolbox.router.any("/user/logout", toolbox.logoutHandler);
toolbox.router.any("/user/*", toolbox.networkOnly);

See Jeff's comment on this issues: "The routing to handlers should match in the order they're registered"
Comment: Thanks Stef. Tested and confirmed. Turns out my service worker wasnt updating during my previous tests of shuffling the order of these around.


Capturar apenas linha

Question: Estou com uma tabela criada em array, e o botão modal abre uma tabela para seleção de unidades de peso / medida, mas quando a seleção é capturada preenche a tabela toda como na foto abaixo. Como faço para preencher somente a linha ?

Estrutura da tabela aberta ao clicar no modal

             Unidade
             Descrição

   <?php
       include ("conn.php");

       $result = "SELECT * FROM cadunid ORDER BY descricao";
       $resultado = mysqli_query($conn, $result);

       while($row = mysqli_fetch_assoc($resultado)) {
           echo "
";
               echo "". $row['codigo'] ."	";
               echo "". $row['descricao'] ."	";
           echo "
";
       }
   ?>

estrutura da tabela mostrada na imagem acima

         <button type="button" class="" data-toggle="modal" data-target="#myModal">Unidade >>                 </button>
         Preço Custo
         Preço Venda
         Peso Bruto
         Peso Liquido
         Qtd. Emb.

    <?php for($i = 0; $i <= 5; $i++){ //coloquei este valor para testar ?>

      <input type="hidden" maxlength="6"  name="recnum[]" style="border:none; width:100%; background-color: transparent;">
      <input type='text' name="unidad[]" class="unidade-input" style="border:none; width:100%; background-color: transparent;">
      <input type="text" maxlength=""  name="preco_custo[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      <input type="text" maxlength=""  name="preco_venda[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      <input type="text" maxlength=""  name="peso_bruto[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      <input type="text" maxlength=""  name="peso_liquido[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      <input type="text" maxlength=""  name="qtde_embalagem[]" placeholder="" style="border:none; width:100%; background-color: transparent;">

     <?php } ?>

script utilizado para capturar unidade selecionada pelo usuário

Comment: tanta colocar ID's nas linhas... ai depois quando for preencher pega a tr com x ID
Comment: não tem como colocar id num loop for, teria de ser class, pois ID é único de um elemento já class poderia ser definido para todos os elementos do array, por isso está setado com class
Comment: loop for que eu saiba ele vai aumentando... usa a variavel do proprio loop como ID, mas se voce diz que n da entao n usa :D
Comment: Já tentei fazer o teste com ID, e ele não captura a seleção do usuário, já com class sim, pois class é utilizado para todos elementos percorridos no while, e id faria com que todos elementos trazidos na tabela do modal tivesse o mesmo id, ou seja, isso é impossível, trazer um while com ID ao invés de class, entende ? Meu problema é trazer apenas uma linha e não em capturar o dado
Answer: Atenderia o seu caso se você inserisse uma linha dinamicamente cada vez que o usuário termina de preencher os dados do modal?

Ao clicar no botão de unidade abrir o modal com os campos a serem
  preenchidos, após o preenchimento dos campos utilizando o próprio javascript
  inserir uma linha na tabela.

Assim você permite o usuário inserir quantas linhas quiser. E inicialmente sua tabela terá apenas o conteúdo do cabeçalho.
Comment: quando não der uma resposta coerente para a pergunta apenas comente @Henrique Oliveira

Capturar apenas linha


Trying to connect to MQ using PHP; almost there

Question: So I've spent the past few days trying to solve this that seems to have been forgotten since none of the two PECL extensions available (SAM and mqseries) have been updated for a long time. I've tried both and mqseries seems to get me the furthest at this point since SAM refuses to get me a connection, even though MQ works perfectly from the command line. I've successfully created a connection to my QueueManager and it's during the next step (MQOPEN) that I fail miserably:
$mqcno = array(
        'Version' => MQSERIES_MQCNO_VERSION_2,
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array('ChannelName' => '[channel]',
        'ConnectionName' => '[ipnumber]([port])',
        'TransportType' => MQSERIES_MQXPT_TCP)
    );

mqseries_connx('MQED', $mqcno, $conn, $comp_code,$reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
    printf("Connx CompCode:%d Reason:%d Text:%s
\n", $comp_code, $reason, $reason);
    exit;
}

$mqods = array('ObjectName'=>'MYPUTQUEUE', 'ObjectType'=>MQOT_Q, 'ObjectQMgrName'=>'MYQUEUEMANAGER');
mqseries_open($conn, $mqods,
          MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
          $obj, $comp_code,$reason);

THis results in $reason being populated with 2044, which translates to MQRC_OD_ERROR, or in English: 'On the MQOPEN or MQPUT1 call, the object descriptor MQOD is not valid'.
So the question is, what's wrong with my MQOD?
Update #1: At this point this is not resolved. I rebuilt the project from the ground up to resolve any issues at build time. I am still stuck on MQOPEN returning 2044. The samples still run flawlessly from CLI, so this is definitely tied to the installation of the PECL extension. If there's anyone out there who has successfully installed and are running PHP against MQ in a fairly recent 64-bit PHP5 environment please let me know...
Update #2: MQPUT1 works flawlessly with the problem that I can't receive my response. At this point, it's just MQOPEN that doesn't work. Question is; what is causing MQOPEN to return 2044 when MQPUT1 works, which I understand includes MQOPEN?
Comment: Yes, sorry. I've edited my question.
Comment: *I've successfully created a connection to my QueueManager and it's during the next step (MQCONN) that I fail miserably...* Do you by any chance mean that it's on the MQOpen that it fails?
Comment: I'm not familiar with the PHP modules but 'DeviceName' seems an odd key for the queue name.
Comment: Perhaps that's the issue. But this is how the official example does it: http://www.php.net/manual/en/function.mqseries-open.php
Comment: But in that example, the hash key is ObjectName, which matches the cmqc.h field name.  Where did DeviceName come from?
Comment: I actually had that, but no difference. I am iterating through the entire struct now, to see if there's something I've forgotten. But also, if Objectname is my PUT queue, what's ObjectType?
Answer: The MQOD in the cmqch file looks like this:
 /****************************************************************/
 /*  MQOD Structure -- Object Descriptor                         */
 /****************************************************************/

 typedef struct tagMQOD MQOD;
 typedef MQOD  MQPOINTER PMQOD;
 typedef PMQOD MQPOINTER PPMQOD;

 struct tagMQOD {
   MQCHAR4   StrucId;              /* Structure identifier */
   MQLONG    Version;              /* Structure version number */
   MQLONG    ObjectType;           /* Object type */
   MQCHAR48  ObjectName;           /* Object name */
   MQCHAR48  ObjectQMgrName;       /* Object queue manager name */
   MQCHAR48  DynamicQName;         /* Dynamic queue name */
   MQCHAR12  AlternateUserId;      /* Alternate user identifier */
   /* Ver:1 */
   MQLONG    RecsPresent;          /* Number of object records
                                      present */
   MQLONG    KnownDestCount;       /* Number of local queues opened
                                      successfully */
   MQLONG    UnknownDestCount;     /* Number of remote queues opened
                                      successfully */
   MQLONG    InvalidDestCount;     /* Number of queues that failed to
                                      open */
   MQLONG    ObjectRecOffset;      /* Offset of first object record
                                      from start of MQOD */
   MQLONG    ResponseRecOffset;    /* Offset of first response record
                                      from start of MQOD */
   MQPTR     ObjectRecPtr;         /* Address of first object record */
   MQPTR     ResponseRecPtr;       /* Address of first response
                                      record */
   /* Ver:2 */
   MQBYTE40  AlternateSecurityId;  /* Alternate security identifier */
   MQCHAR48  ResolvedQName;        /* Resolved queue name */
   MQCHAR48  ResolvedQMgrName;     /* Resolved queue manager name */
   /* Ver:3 */
   MQCHARV   ObjectString;         /* Object long name */
   MQCHARV   SelectionString;      /* Message Selector */
   MQCHARV   ResObjectString;      /* Resolved long object name*/
   MQLONG    ResolvedType;         /* Alias queue resolved object type */
   /* Ver:4 */
 };

 #define MQOD_DEFAULT {MQOD_STRUC_ID_ARRAY},\
                      MQOD_VERSION_1,\
                      MQOT_Q,\
                      {""},\
                      {""},\
                      {"AMQ.*"},\
                      {""},\
                      0,\
                      0,\
                      0,\
                      0,\
                      0,\
                      0,\
                      NULL,\
                      NULL,\
                      {MQSID_NONE_ARRAY},\
                      {""},\
                      {""},\
                      {MQCHARV_DEFAULT},\
                      {MQCHARV_DEFAULT},\
                      {MQCHARV_DEFAULT},\
                      MQOT_NONE

I'm wondering if the module fills in the defaults and is letting you override then with the hash.  If so, is 'DeviceName' really the right key?  I would think it would match the WMQ field name or constant.
Update: Per the example at the link provided, the hash key does indeed match the field name from the cmqc.h.
Update #2 respond to comment: Object types as defined in cmqc.h are:
 /* Object Types */
 #define MQOT_NONE       0
 #define MQOT_Q          1
 #define MQOT_NAMELIST   2
 #define MQOT_PROCESS    3
 #define MQOT_STORAGE_CLASS 4
 #define MQOT_Q_MGR      5
 #define MQOT_CHANNEL    6
 #define MQOT_AUTH_INFO  7
 #define MQOT_TOPIC      8
 #define MQOT_CF_STRUC   10
 #define MQOT_LISTENER   11
 #define MQOT_SERVICE    12
 #define MQOT_RESERVED_1 999

My understanding of the PHP, Perl and most other similar efforts is that they are a very thin wrapper over the C API.  The Perl one simply generates most of the code directly from the cmqc.h and other C include files and therefore all the field names and defaults exactly match those include files.  This module appears to have taken a similar approach and I would expect to use the defined names and field defaults where needed.
I'm thinking something like:
$mqods = array(
                 'StrucID'=>'OD  ',
                 'Version'=>1.
                 'ObjectType'=>1,
                 'ObjectName'=>'MYPUTQUEUE',
                 'ObjectQMgrName'=>'MYQUEUEMANAGER'
                 'DynamicQName'='',
                 'AlternateUserId'='',
                 'RecsPresent'=>0,
                 'KnownDestCount'=>0,
                 'UnknownDestCount'=>0,
                 'InvalidDestCount'=>0,
                 'ObjectRecOffset'=>0,
                 'ResponseRecOffset'=>0,
                 'ObjectRecPtr'=>NULL,
                 'ResponseRecPtr'=>NULL
);

Update #3 respond to additional comments:
The Q Mgr will accept any version of the MQOD but will fall back to that level of functionality.  If you use v1 you can test out that it works.  If you want to use later versions of the MQOD then you will need to add the additional fields to the hash.
The 2009 is "Connection Broken."  Essentially the QMgr didn't like something and terminated your connection.  Usually the meaningful error messages for that return code are in /var/mqm/qmgrs/<qmgrname>/errors/AMQEER01.LOG.
Comment: they do. Changed the hash table to the following to no avail: $mqods = array('ObjectName'=>'MYPUTQUEUE', 'ObjectType'=>MQOT_Q, 'ObjectQMgrName'=>'MYQUEUEMANAGER');
Comment: Unless the constant MQOT_Q is defined, that value would be a 1.
Comment: Changing Version to 4 caused another error; 2009, which at least means that it accepts the MQOD. 4 means 'Current Version' if I read cmqc.h correctly


Liberar link após preenchimento de formulário

Question: Sou iniciante em Javascript/jQuery e estou com dúvida de como fazer para liberar um link logo após todos inputs estiverem preenchidos, caso contrário ele se mantém bloqueado:
Segue HTML:
<form id="formulario">
    Usuário
    <input id="usuario">
    Senha
    <input id="senha">
    <button type="button" id="login">Login</button>
</form>

Answer: Você pode usar o bootstrapValidator. É simples e fica muito bom visualmente
$('#formulario').bootstrapValidator({
        message: 'O valor informado não é válido!"',
        feedbackIcons: {
            valid: 'fa fa-check-circle fa-lg text-success',
            invalid: 'fa fa-times-circle fa-lg',
            validating: 'fa fa-refresh'
        },
        fields: {
            usuario: {
                validators: {
                    notEmpty: {
                        message: 'Preencha o usuário antes de continuar!'
                    }
                }
            },
            senha: {
                validators: {
                    notEmpty: {
                        message: 'Preencha a senha antes de continuar!'
                    }
                }
            },
        }
    }).on('success.field.bv', function(e, data) {
        var $parent = data.element.parents('.form-group');
        $parent.removeClass('has-success');+ '"]').hide();
    }).on('error.form.bv', function(e) {
        isValid = false;
    });

Se por acaso o usuário clicar em login antes de preencher os campo, o botão é desabilitado a as mensagens que foram setadas na função serão mostradas em baixo do input.
Comment: +1 Não conhecia! Parece ser interessante
Answer: É possível resolver seu problema apenas com um atributo HTML5 chamado required.
<form id="formulario" action="http://meusite.com.br">
    Usuário
    <input id="usuario" required>
    Senha
    <input id="senha" required>
    <input type="submit" id="login" value="Login">
</form>

Dessa forma o browser faz a validação verificando se campo obrigatório está preenchido.
Comment: lembrando que o required é um atributo novo do HTML5
Comment: Sem problemas @WallaceMaxters, é a mesma pergunta interpretada de duas formas diferentes, no fim das contas o que importa é mostrar formas diferentes de se resolver o mesmo problema, uma resposta inteiramente completa teria todas as soluções possíveis para este problema. A sua resposta não esta errada e nem a minha, as duas são complementares já que se você tiver um formulário bem formatado a funcionalidade vai ser a mesma que fazendo a validação por javascript e ativando/mostrando um link apenas com um form válido.
Comment: Não faltou @WallaceMaxters, quem faz esse trabalho é o *browser*, enquanto o formulário não for válido o `submit` não vai enviar e o *browser* vai solicitar que os campo sejam preenchidos, ou seja, o submit fica desabilitado.
Comment: e onde iria o link neste caso, @Erlon Charles? Creio ser isso que o Wallace quis dizer...
Comment: No action do Form, vou editar e colocar uma url falsa
Comment: @WallaceMaxters acho que você ta implicando com pouca coisa velho kkk o atributo Required do HTML5 serve justamente para o mesmo proposito.... So existem "dois problemas" ao usar o required.... primeiro se a requisição for feita em Ajax, segundo se o browser do usuário não suportar as tags de HTML5, coisa que hoje é pouco provável.
Comment: Só há problema em usar o ajax no formulário se você colocar a ação dele no `.click`. Se você usar o `$("form").submit` a ação só será enviada quando o form estiver válido. Eu já fiz isso várias vezes
Comment: Agora se, o caso for usabilidade e não apenas a funcionalidade (o que não ficou claro na pergunta) é um caso diferente.
Comment: Para mitigar a intenção do usuário de clicar em um botão com um formulário não completo ainda o ideal era que o botão fosse mostrado apenas depois de todo formulário ter sido preenchido corretamente, fazendo a validação a cada `focus` ou a cada `keyup`.
Answer: Se eu entendi direito que você quer liberar um link sendo liberado após os dados preenchidos, faça o seguinte. Altere seu HTML para:
<form id="formulario">
    Usuário
    <input required id="usuario">
    Senha
    <input id="senha" required>
    <button type="button" id="login">Login</button>
</form>

Seu link Bloqueado

E, com o jQuery, faça o seguinte:
$(function(){

    $('#login').click(function(e){

       if ($("#usuario").is(':valid') && $("#senha").is(':valid')) {
           // Ação ao submter o formulário
           $("#seu_link").removeClass('disabled');
       } else {
          e.preventDefault();
       }
    });

   $(document).on('.disabled', 'click', function(){ return false; });

});

Assim você está verificando se o input está preenchido.
Nota: A verificação com is(':valid') ou is(':invalid') só é possível se o input possuir o atributo required ou o pattern.
Segue o exemplo do JSFiddle
No caso, como imaginei que talvez você, ao invés de querer desbloquear um link, desbloquear o botão que faz o submit.
Então elaborei o seguinte código.
Formulário:
<form id="formulario">
    Usuário
    <input required id="usuario">
    Senha
    <input id="senha" required>
    <button type="button" id="login" disabled>Login</button>
</form>

JQuery:
$(function(){

    var $btn = $("#login");

    $("#usuario, #senha").on('keyup', function(){
        if ($('#usuario').is(':valid') && $('#senha').is(':valid')) {
            $btn.attr({disabled:false});
        } else {
            $btn.attr({disabled: true});
        }
    });

});

Você pode ver esse segundo exemplo nesse JSFiddle
Penso que dessa segunda forma, a usabilidade é maior
Comment: Você esqueceu de colocar a classe `disabled` no link que ficará desabilitado.
Comment: rsrsrs, valeu @ErlonCharles
Comment: @WallaceMaxters, poderia colocar um exemplo no jsfiddle?
Answer: Existem várias formas de se fazer isso Éder...
Uma delas é usando uma biblioteca chamada Jquery-Validate, existe tbm uma outra biblioteca que eu gosto que se chama validationEngine
Na mão, utilizando apenas recursos do JQuery você pode fazer algo do tipo:

$(document).ready(function(){
    $("#login").click(function(e){
     // bloqueando envio do form
     e.preventDefault();
     var erros = 0;
     // verifica se ha campos vazios
     $("#formulario input").each(function(){
      // conta erros
      $(this).val() == "" ? erros++ : "";
     });
     if(erros > 0 ){
      alert("Existe "+erros+" campo(os) vazio neste fomulário");
        }else{
      $("#formulario").submit()
     }
    });
});

<form id="formulario">
Usuário
<input id="usuario">
Senha
<input id="senha">
<input type="button" id="login" value="Login">
</form>


Erro de autenticação no WSDL

Question: usando o phptester para testar o seguinte código:
<?phptry {
$opts = array(
    'http' => array(
        'user_agent' => 'PHPSoapClient'
    )
);
$context = stream_context_create($opts);

$wsdlUrl = 'http://ws.portaledu.com.br:8051/wsConsultaSQL/MEX?wsdl';
$soapClientOptions = array(
    "login"      => "XxXxXxXx",
    "password"  => "XxXxXxXxX",
    "stream_context" => $context,
    "cache_wsdl" => WSDL_CACHE_NONE
);

$client = new SoapClient($wsdlUrl, $soapClientOptions);

echo $status =(string) simplexml_load_string($client->RealizarConsultaSQL(['codSentenca'=>'06','codColigada'=>$CODCOLIGADA,'codSistema'=>'S','parameters'=>'CODCOLIGADA='.$CODCOLIGADA.';IDPS='.$IDPS.';CPF='.$CPF.';DTNASCIMENTO='.$DTNASCIMENTO])->RealizarConsultaSQLResult)->Resultado->DESCRICAO;

}
catch(Exception $e) {
    echo $e->getMessage();
}

recebo o retorno:

WARNING SoapClient::SoapClient(http://ws.portaledu.com.br:8051/wsConsultaSQL/MEX?wsdl): failed to open stream: Connection refused on line number 17

Porque será que não autentica, será que preciso liberar mais alguma porta além da 8051 para fazer requisições SOAP?
Answer: Quando o conteudo está num endpoint de um ws, via php o mais coerente é fazer via CURL...
<?php
    $runfile = 'http://ws.portaledu.com.br:8051/wsConsultaSQL/MEX?wsdl';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    curl_close ($ch);

    echo $content;

Comment: a dica foi muito boa, mas deixa eu completar a pergunta pra a gente marcar de vez essa resposta como solução,a posto que vai conseguir completar o raciocínio.
Comment: aquele seu echo parece um tanto estranho... vou copiar ele e tentar entender
Comment: Ele é um pouco confuso mesmo, no entanto, o objetivo é: enviar uma requisição `SOAP` para esse `wsdl` que já mencionei acima, e chamar a função `RealizarConsultaSQL()` e mostrar na tela o seu retorno!
Comment: sugiro resolver um problema por vez... dar um echo no retorno primeiro e qdo estiver retornando o que espera partir apenas para a função, ai fica mais organizado o raciocínio. Sobre exibir o maior, dependendo de como vier o retorno vc pode transformar em array e apenas eleger o maior da lista.
Comment: Estou entendendo, mas me ajuda a compreender aqui, porque esse código não me retornou erro, muito menos xml (não retornou nada), como irei fazer a requisição para o `RealizarConsultaSQL()`
Comment: na verdade o xml ta retornando ate qdo eu colo direto no navegador, entao pelo CURL tmb estará! a partir dai vc só precisa processar o retorno dela.
Comment: Tente entender este processo e como ele gera o seu código para consumir o serviço:
 https://code.google.com/archive/p/php-wsdl-creator/

Erro de autenticação no WSDL


Wireguard reports transmission errors while underlying interface reports none

Question: I'm investigating an intermittent network failure, and when looking at /proc/net/dev file I see that WireGuard interface reports variable number of transmission errors for all VMs in the cluster (it scales more or less with the volume of traffic moving though this interface).
However, it reports no errors on receiving side. And the underlying interface reports no errors whatsoever.
How should I interpret this situation? Is this expected? Is this a bug in WireGuard? Can this possibly be the reason for intermittent loss of connectivity?
ip -s -s link show wg0
4: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1
    link/none
    RX: bytes  packets  errors  dropped overrun mcast
    18229925236 135673958 0       0       0       0
    RX errors: length   crc     frame   fifo    missed
               0        0       0       0       0
    TX: bytes  packets  errors  dropped carrier collsns
    951387346088 775255612 26278   0       0       0
    TX errors: aborted  fifo   window heartbeat transns
               0        0       0       0       0

This is here just to give you some illustration of what I'm seeing.
Answer: WireGuard uses UDP, so the sending side will almost never report any errors - and the receiving side will so, too. If packets get lost (dropped) on their way, the receiving WireGuard Interface will report that, your physical interfaces will not.
And yes, dropped packets can (and amost certainly will be) the culprit here.
Comment: Most probably a wireguard interface would only report dropped packets when a receiver rejected incoming packets with ICMP messages. Because of the lower MTU of a VPN interface it is important that all clients using the tunnel have PMTUD enabled. Or you could set the VM interfaces also to a MTU of 1420 to match.
Comment: But it has a specific column for dropped packets, why not report it there? Also, the errors appear in TX, not RX (so the reporter is the transmitter, not the receiver). The receiving interface reports no errors. Sorry I wasn't clear: "transmission errors" here are used literally to mean errors in TX column, not "errors generally happening when transmitting packets".
Comment: "But it has a specific column for dropped packets, why not report it there?" - Sounds like they are not dropped, but changed (which makes them unuseable in the VPN).
Comment: This doesn't seem to explain the situation... if the MTU was the problem, then I'd expect to see *a lot more* errors. Also, my impression so far was that errors reported in TX section are of a kind "I needed to write Ethernet frame, but ARP request didn't know how to map my MAC to IP" or something like that. I.e. errors that happen *before* the packet is sent, not after it is sent but then reported as erroneous (in that case, I'd expect the receiver to also have record of the problem, which it hasn't).


How to customize infoWindow (but without using google-maps-utility-library-v3)?

Question: I would like to customize my infoWindow adding "border-radius" and "background-color", but in each similar question that I have searched here, the answer is to use google-maps-utility-library-v3...
I know that is a good solution, (infact for other reasons I use that), but I would like to know if is there another way to achieve what I want to do...
I tried in this way, with jquery:
var infoWindow;  //like global variable

var centrocircle= new google.maps.LatLng(X,Z);
    var circleOptions = new google.maps.Circle({
        strokeColor: colore,
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: colore,
        fillOpacity: 0.85,
        map: map,
        center: centrocircle,
        info: '
home
',
        radius: raggio*770
    });

google.maps.event.addListener(circleOptions, 'domready', function() {
    var l = $('#hook').parent().parent().parent().siblings();
    for (var i = 0; i < l.length; i++) {
        if($(l[i]).css('z-index') == 'auto') {
            $(l[i]).css('border-radius', '16px 16px 16px 16px');
            $(l[i]).css('border', '2px solid red');
        }
    }
});

google.maps.event.addListener(circleOptions, 'click', function() {
    infoWindow.setPosition(this.center);
    infoWindow.setContent(this.info);
    infoWindow.open(map,this);
})

but doesn't work....
I hope can you help me... thanks!
EDIT
var infoWindow;  //like global variable

var tooltipHTML =
    '
'+
    '
'+
    '
'+
    '
NAME           CUSTOMER
'+
    '
'+
    '
MORE INFO OF: CUSTOMER
'+
    '
'+
    '
';

And
var centrocircle= new google.maps.LatLng(X,Z);
var circleOptions = new google.maps.Circle({
   strokeColor: colore,
   strokeOpacity: 1,
   strokeWeight: 2,
   fillColor: colore,
   fillOpacity: 0.85,
   map: map,
   center: centrocircle,
   info: tooltipHTML,
   radius: raggio*770
});

google.maps.event.addListener(circleOptions, 'click', function() {
   infoWindow.setPosition(this.center);
   infoWindow.setContent(this.info);
   infoWindow.open(map,this);
})

Comment: I think you would need a infobox for that. Styling the infowindow itself is hideous task and you just end up seeing all your effort was waste of time the day google decides to do things a little bit different, and that day _will_ come, sooner or later.
Answer: You can customize de infowindow applying some CSS rules to the following class ".gm-style-iw". Recently I wrote a post explaining just that, you can read it here - 5 ways to customize Google Maps InfoWindow
Comment: Yes, but what then `.gm-style-iw` is changed to `.gm-st-iw` or similar? And how to distinct properly between multiple infowindows?
Comment: @MigMar yes is a great solution, but i have only little problem... When i click on the marker (in my situation circle) it opens the infoWindow, but the map goes down for same pixel... Do you know what is the problem? Thanks
Comment: @davidkonrad that's a good point. That's why I'm forcing the usage of the version that is compatible with my code (?v=3.20 actual experimental version). Then I have 3 to 9 months to test new versions. This solution wasn't tested with multiple infowindows, may not be a right solution for that.
Comment: @MigMar, +1 fine work. Was trying something similar, but stopped when I realized It was hard to distinguish between infowindows, like one with red border, another with green border and so on. But nice styling of std. infowindows anyway! You should add a code example to your answer to attract more upvotes :)
Comment: @Mapsism Borja normally the map goes down because of the height of the infowindow. Do you have any online example?
Comment: @Mapsism Borja  to add color to tail you just have to add a background color to this line: iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': 'rgba(72, 181, 233, 0.6) 0px 1px 6px', 'z-index' : '1', 'background-color' : 'blue'}); Please pay atention to what davidkonrad said, you have to track updates to the API to make sure this workaround will be fine in future updates.
Comment: @davidkonrad thanks, i think you can style different infowindows adding a class to .gm-style-iw depending of the type of the marker. For example markers of the type of Culture are blue and markers of Sport are red. For now this is just a theory, but you gave me a good idea for the next post update.
Comment: @MigMar to change the color of tail shadow ? i must to change box-shadow or background color? and line is same (when change only         **':nth-child(1)'**  ?
Comment: The tail shadow have two components, there is a front DIV with white color and it has a shadow. This shadow can be changed with the following line:
iwBackground.children(':nth-child(3)').find('div').children().css({'z-index' : '1', 'box-shadow' : 'rgba(10, 84, 199, 0.32) 0px 1px 6px'});
You must change box-shadow values.
Comment: The second DIV is bellow of the first DIV and you can change its color with the following line:
iwBackground.children(':nth-child(1)').attr('style', function(i,s){ return s + 'left: 76px !important; border-top-color: rgba(10, 84, 199, 0.0980392)'});
You must change border-top-color values.

I believe this second DIV is a shadow for some older browsers that don't support the box-shadow propriety.
Comment: Considering the comments on your blog post, people are still reading your tutorial and trying to use it. This is all UNDOCUMENTED and should NOT be used. You should delete your blog post as well as this answer as it is all very BAD practice. CSS class names, selectors, etc. are subject to change at any time without notice from Google.
Answer: Better use a Tooltip:
Declare HTML structure as desired for it:
var tooltipHTML =
    '
'+
    '
'+
    '
'+
    '
NAME CUSTOMER
'+
    '
'+
    '
MORE INFO OF: CUSTOMER
'+
    '
'+
    '
';

You will need an empty infoWindow:
var infowindow = new google.maps.InfoWindow({});

Then insert the tooltip:
bindInfoWindow(circleOptions, map, infowindow, tooltipHTML);

bindInfoWindow function adds a listener to the element.
function bindInfoWindow(circle, map, infowindow, strDescription) {
    google.maps.event.addListener(circle, 'click', function() {
        infowindow.setContent(strDescription);
        infowindow.open(map, marker);
    });
}

EDIT: Sometimes, there are problems with Circle tooltip's, so, if above code does not work, I've found HERE a possible workaround with title attibute:
google.maps.event.addListener(circle,'mouseover',function(){
     this.getMap().getDiv().setAttribute('title',this.get('title'));});

google.maps.event.addListener(circle,'mouseout',function(){
     this.getMap().getDiv().removeAttribute('title');});

Comment: Jordi sorry for my ignorance, but where are style CSS for id in "tooltipHTML" ??
Comment: sure! you can use `style="color:red"` or define a `class="red"` as usual in your wiew and declare `.red` class in your `CSS stylesheet` .
Comment: Jordi see my EDIT.. it should work, what do yuo think?
Comment: It should, but after investigating a bit, there can be problems sometimes, check the workaround in the edit...
Comment: Jordi i tried but doesn't work with your code, i tried also add "tooltipHTML" to info (like can you see in my EDIT), but the style is also for infoWindow's content, not for all infoWindow :/
Comment: have you tried with workaround in my edit? maybe `this.getMap().getDiv().setAttribute('title' ,tooltipHTML);});` ??
Comment: did you check the link???? `The tooltip is created via the native title-attribute of DOM-elements, but the` **API doesn't provide any method to access the DOMElement that contains the circle**.

`A possible workaround may be to use the title-attribute of the map-div instead(set it onmouseover and remove it onmouseout)`
Comment: Yes you are right, sorry :( but i didn't understand where to insert event.addlistener (mouseover and out), i didn't understand why in new.google.maps.InfoWindow there {} , and now i didn't understand why "title"... Sorry Jordi :( thanks for all
Answer: Another solution which is still a hackish workaround and counts on the current hierarchy / implementation.

JSFiddle
I used this to implement the content exactly as I liked, added my own arrow manually (with CSS) and just modified the location in order to line it up correctly with the marker on the map.
Main idea is to hide all the surrounding content and align manually to marker using the 'pixelOffset' property.
var infoWindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(4, 20),
});

google.maps.event.addListener(displayedInfoWindow, 'domready', function() {
    var el = $('.gm-style-iw');
    el.siblings().css('visibility', 'hidden');
    el.click(function() {
        displayedInfoWindow.close();
    });
});

displayedInfoWindow.setContent(myHtmlContent);
displayedInfoWindow.open(myMapObj, marker);

Comment: This is as bad as @MigMar answer. Undocumented. Do not use.


Point on a line with the least distance from another point in $\mathbb{R}^3$

Question: Consider the line $L$ defined by the following parametric equations
$$x= 3+2t$$
$$y= 4+t$$
$$z=5-6t$$
Find the point $Q$ on $L$ that is closest to $(4,1,7)$.
Note: I do not really remember the formulas, I need help!
Comment: @marvis There has been strong [consensus on meta in the past](http://meta.math.stackexchange.com/questions/1617/what-is-the-site-etiquette-about-i-asking-and-ii-answering-questions-in-a-la) that people generally prefer coherent questions in foreign languages, which can be intelligently translated to English (as this one was) to incoherent, unintelligible questions in English.
Comment: Could you write in English?
Comment: Consider the line L defined by the following parametric equations

x=3+2t
y=4+t
z=5−6t

I want to find the point Q that lies on L that is closest to (4,1,7).

Note: Really, I don't remember the formulas, I need help!
Answer: The plane containing this closest point will have normal vector
$$n = 2i + j - 6k. $$
Since the point $(4,1,7)$ is in the plane and the plane's equation is
$$ 2x + y - z = 2\cdot4 + 1 - 7 = 1.$$
The closest point will lie where the point and line intersect. Find this, then the distance to the point $(4,1,7)$.
Answer: The distance between $(x,y,z)$ and $(4,1,7)$ is $\sqrt{(x-4)^2+(y-1)^2+(z-7)^2}$.  That follows from the Pythagorean theorem.  This is the same as
$$\sqrt{(2+2t-4)^2+(4+t-1)^2+(5-6t-7)^2}.$$
That simplifies to
$$
\sqrt{(2t-2)^2+(3+t)^2+(-2-6t)^2}.
$$
The value of $t$ that minimizes the distance is the same as the value of $t$ that minimizes the square of the distance, i.e. $(2t-2)^2+(3+t)^2+(-2-6t)^2$.  If you multiply that out, you get $(\bullet t^2) + (\bullet t) + (\bullet)$.  Find the three numbers and then complete the square.
Answer: Thanks to Michael Hardy, in (poor) spanish:
La distancia entre $(x,y,z)$ y $(4,1,7)$ es $\sqrt{(x-4)^2+(y-1)^2+(z-7)^2}$.  Este sigue de la teorema de Pythagorean.  Esto es lo mismo que
$$\sqrt{(2+2t-4)^2+(4+t-1)^2+(5-6t-7)^2}.$$
Simplifica a
$$
\sqrt{(2t-2)^2+(3+t)^2+(-2-6t)^2}.
$$
El valor de $t$ que minimiza la distancia es lo mismo que el valor de $t$ que minimiza el el cuadrado de la distancia: $(2t-2)^2+(3+t)^2+(-2-6t)^2$.  Si multiplica eso, consique $(\bullet t^2) + (\bullet t) + (\bullet)$.  Encuentra estos numeros y completa el cuadrado.
Tambien, disculpa mi traduccion mala.
Answer: Direction cosines of given line are $(2,1,-6)$. If $P=(4,1,7)$ and $Q=(3+2t,4+t,5-6t)$ be the closest point on the line to P, then line joining these two points must be normal to direction cosines of given line. Hence, dot product of vectors $PQ=(2t-1,3+t,-6t-2)$ and $(2,1,-6)$ would be $0 \implies$ $4t-2+3+t+36t+12=0 \implies 41t=-13 \implies t=-13/41$ for $Q$.Thus, the point is  $(97/41,151/41,283/41)$.


Gridiview em asp.net montagem

Question: Boa tarde Pessoal.
Estou com uma duvida na hora de montar um gridview não possuo muitos conhecimentos em c# eu fiz dessa maneira
 string sql = "SELECT pr.codigo_chave,pr.codigo_produto,pr.nome_produto,ca.nome_categoria FROM infobook_net.produtos pr inner join categorias ca on pr.codigo_categoria = ca.codigo_categoria";
    Response.Write(sql);

    cmd.CommandText = sql;
    cmd.Connection = sqlConnection1;
    try
    {
        sqlConnection1.Open();
        MySqlDataReader reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                GridView1.DataSource = reader;
                GridView1.DataBind();
            }
        }
        else
        {
            Response.Write("não foram encontrados dados");
        }
    }
    catch (Exception ex)
    {
        Response.Write(Convert.ToString(ex));
    }

Ele esta rodando e preenchendo o gridview somente quando tem mais de uma linha de retorno quando so tem uma ele não monta nada e não mostra nada alguem tem uma ideia de como fazer?
obrigado
Answer: Você não precisa iterar sobre o DataReader para fazer o DataBind. Basta definir o DataSource e chamar o método DataBind conforme abaixo:
String sql = "SELECT pr.codigo_chave,pr.codigo_produto,pr.nome_produto,ca.nome_categoria FROM infobook_net.produtos pr inner join categorias ca on pr.codigo_categoria = ca.codigo_categoria";
Response.Write(sql);

cmd.CommandText = sql;
cmd.Connection = sqlConnection1;
Try
{
    sqlConnection1.Open();
    MySqlDataReader reader = cmd.ExecuteReader();

    If (reader.HasRows)
    {
        GridView1.DataSource = reader;
        GridView1.DataBind();
    }
    Else
    {
        Response.Write("não foram encontrados dados");
    }
}
Catch (Exception ex)
{
    Response.Write(Convert.ToString(ex));
}

Comment: Obrigado Richard deu certo Obrigado

Gridiview em asp.net montagem


How can I run two different tasks in pyTelegramBotAPI?

Question: I want to run two different tasks in pyTelegramBotAPI. But the task after the bot run task is not running.
import telebot, asyncio, datetime

bot = telebot.Telebot(token)

def task1():
    bot.polling()

def task2():
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))

if __name__ == '__main__':
    asyncio.run(task1) # This task is running
    asyncio.create_task(task2()) # This is not working

After the bot runs, subsequent tasks do not run.
Comment: Your functions task1 and task2 are not asyncio tasks, because they (1) are not declared async def, and (2) do not contain await expressions.  Even if you fixed that, your call to asyncio.run() will execute task1 to completion before proceeding.  You should perhaps look at an asyncio tutorial to see how to get started.
Answer:
Mark functions with async async def task1():
Create main async function and start tasks in it

import telebot, asyncio, datetime

bot = telebot.Telebot(token)

async def main():
    await asyncio.gather(*(task1(), task2())) # You can optionally add return_exceptions=True

async def task1():
    bot.polling()

async def task2():
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))

if __name__ == '__main__':
    asyncio.run(main())

Comment: I did as you said, the problem persists.
Comment: Sorry, found my error, now it's fixed
Comment: Unfortunately it didn't happen again. task1() works but task2() does not.
Comment: Are you sure that your second task do something? add print at the start of task1 and task2 and check if they are called, if they print, so it's problem in something else
Comment: Yes, I'm sure, it doesn't switch to task2() after task1()
Comment: What do you need actually? I already answered how to run 2 tasks, 2 tasks in parallel, and how to just run tasks, I just don't understand what you need
Comment: Your two tasks will not cooperatively multitask because neither one contains an await expression.  Just putting async in front of the function definition does not cause it to yield control to the event loop.  Only an await expression does that.
Answer: I'm sorry to post instead of commenting on your post, but I don't have enough reputation to do so.
Your code has a mistake in task2, it only checks once and (I assume) you want it to check indefinitely.
This is the code you should write instead:
async def task2():
while True:
    now = datetime.datetime.now()
    if now.hour == 12 and now.minute == 30:
        bot.send_document(admin_id, open("work_db.db", "rb"))
    else:
        await asyncio.sleep(60)

This code checks the time every minute, but you can tweak it to check less times and/or to be more precise. With this function, Kalosst0's answer should work.


Derivative of Convolution of Distribution and Test Function on $\mathbb R$

Question: Let $T\in\mathcal D'(\mathbb R)$ be a distribution and let $f\in C^\infty_c(\mathbb R)$ be a test function.
How may I show that
$$(T*f)'=T'*f=T*f'\tag*{?}$$
This is what I did:
$$\begin{align*}(T*f)'(x)&=\lim_{h\to0}\frac{T*f(x+h)-T*f(x)}{h}\\&=\lim_{h\to0}\frac{\int T(y)f(x+h-y)-\int T(y)f(x-y)}{h}\\&=\lim_{h\to0}\frac{\int T(y)(f(x-y+h)-f(x-y))}{h}\\&=\int T(y)\lim_{h\to0}\frac{f(x-y+h)-f(x-y)}{h}\tag*{DCT}\\&=\int T(y)f'(x-y)\\&=T*f'(x)\end{align*}$$
Since convolution is commutative, one can similarly show that $(T*f)'=T'*f$.
Therefore, $?$ holds.
However, I feel that there is something off about my argument. For example, I did not use the fact that $f$ is compactly supported. Moreover, is $T$ not supposed to take arguments in $C_c^\infty(\mathbb R)$ and not in $\mathbb R$ since $T$ is a linear functional on $C_c^\infty(\mathbb R)$?
Comment: The easiest way is to look at $1_{x\in [0,b]} \ast T \ast f'= T \ast (f(x)-f(x-b))$, and $T' \ast f = T \ast f'$  is by definition of the distributional derivative. Otherwise let $g_a(x) = \frac{f(x+a)-f(x)}{a}$ then $\lim_{a \to 0} g_a = f'$ where the convergence is in $D(\mathbb{R})$. Therefore $(T \ast f)' = \lim_{a \to 0} T \ast g_a = T \ast f'$
Comment: The meaning of $(T\ast f)(x)$ is by definition $T(y\mapsto f(x-y))$. Try to apply this and the fact that the sequence of functions $\{ (y\mapsto [f(x+h-y)-f(x-y)]/h) \vert h\to 0\}$ converges to $(y\mapsto f(x-y))$ in the space $\mathcal{D}$ (why?) ! And now you use the continuity of $T$.
Answer: There's a major technicality in your argument which involves the commuting of limits, which requires you to comment on the different topologies in play (the weak-* topology on $\mathcal{D}'(\mathbb{R})$ compared to the natural projective limit topology of $C^{\infty}_c$). Furthermore, the proof won't be symmetric in $T$ and $g$. Instead, here's how I'd prove it:
For $g\in C^{\infty}(\mathbb{R})$, denote $\tilde{g}(x)=g(-x)$. Then, by definition, for any test-function $\varphi\in C_c^{\infty}(\mathbb{R})$,
$$
\langle T*f,\varphi\rangle= \langle T,\varphi\;*\tilde{f}\rangle
$$
Thus, by definition of the weak derivative and the fact that $g'*\tilde{f}=g*\tilde{f}'$ (since they are both $C^1$ in the usual sense),
$$
\langle (T*f)',g\rangle=-\langle T*f,g'\rangle=-\langle T,g'*\tilde{f}\rangle=-\langle T,g* \tilde{f}'\rangle=\langle T,g * \tilde{(f')}\rangle=\langle T*f',g\rangle
$$
For the other identity, we simply follow the first three equalities above and then realise, again since $f$ and $g$ are $C^1$, that
$$
-\langle T,g*\tilde{f}'\rangle=-\langle T,(g*\tilde{f})'\rangle=\langle T',g*\tilde{f}\rangle=\langle T'*f,g\rangle
$$


SOP violation in paho mqtt

Question: when I am trying to use Paho MQTT javacrript with Mosquito MQTT websockets, everything works as long as the web server that I am using to serve my page and Mosquito are in the same server (same origin). However, if I try to connect to a different Mosquito instance (cross domain), Firefox throws a security error.
Problem is that the Javascript client initiates a http connection to the Mosquito web socket server and it gets upgraded to ws:// as part of negotiation. Had the initial request itself been over ws:// , SOP would not have kicked in.
I tried to connect to the second server from http://mitsuruog.github.io/what-mqtt/ and it works fine without SOP error. So, I know that the server can support ws:// . How to get this done using the Paho implementation?
Is there any way to work around this?
Answer: The issue is that I was trying to initiate an un-secure (ws:// instrad of wss://) while the page was itself loaded over https:// . This results in a mixed content error that is not explicitly reported by Firefox. Chrome prints a better warning and allows to temporarily bypass it as well.

SOP violation in paho mqtt


Join with where query in Laravel returns wrong timestamps

Question: Strange thing happens, I query with the following:
<code>$bananafriends   = IsFree::join('friendships', function($join)use($user) {
                    $join->on('arefree.user_id', '=', 'friendships.user_rec_id')
                        ->where('friendships.user_send_id', '=', $user->id);
                    })
                    ->get();
</code>
It returns the timestamps & ID of the friendship model but not the isFree model.
I don't understand why or how I could retrieve the timestamps from the isFree model if that does not work.
Thanks!
Answer: Right now the selects are overriding each other.
You need to add a select:
<code>$bananafriends = IsFree::join('friendships', function($join)use($user) {
                    $join->on('arefree.user_id', '=', 'friendships.user_rec_id')
                        ->where('friendships.user_send_id', '=', $user->id);
                    })
                    ->select('friendships.*', 'arefree.*', 'arefree.created_at as free_created')
                    ->get();
</code>
See the doc on selects:
http://laravel.com/docs/4.2/queries#selects
If this does not work let me know I will help you troubleshoot it.
Comment: Thanks !! Didn't need the last arefree.created_at. Once you select the arefree.* it took the timestamps! Thank you so much  :-)


Geodesics on surface of revolution of regular curve

Question: I was recently presented with this in differential geometry stating the following:

Let us define the regular curve on the XZ plane as: $ \gamma (t) = (sin(t)+2,0,t) $ on XZ plane for $ t \in R $, and define S the regular surface obtained via rotation of the curve $ \gamma $ about the z axis. We are to determine for which real values of c the intersection curve of S with the plane $ z=c $ is a geodesic on the surface S

I do not know how to proceed all I know is the definition of a geodesic but cannot do this technically can someone please help on this? Thank you kindly
Comment: Hopefully this question http://math.stackexchange.com/questions/53382/geodesic-of-a-curved-surface will provide some help
Answer: First, if $S$ is a regular surface and $c\colon I\subset \mathbb{R}\longrightarrow S$ is a geodesic then $$N (c(s))\parallel \vec{n}(s),\ \ \forall s\in I,\ \ \ \ \ \ \ \ (\dagger)$$ where $N$ is the unit normal of $S$ and $\vec{n}$ the first normal of the curve $c$. Thus, in your problem you are interested in finding the parallels of your surface of revolution that are also geodesics. Equivalently you want to find the parallels that do satisfy $(\dagger)$. Therefore, if $\alpha_t$ is the intersection curve of your $S$ with the plane $z=t$ you want to find the parallels $\alpha_t$ that do satisfy the following: $$N(a_t)\perp \vec{e}_3=(0,0,1)\ (\leftarrow \text{direction of the axis of rotation}).$$
To do that, consider the following parametrization of your surface of revolution  $$X(t,u):=(\underbrace{(\sin t+2)}_{f(t):=}\cos u,(\sin t+2)\sin u,t).$$
The unit normal is $$N(t,u)=\frac{X_t\times X_u}{||X_t\times X_u||}=\frac{1}{f(1+(f')^2)}(-\cos u,-\sin u,f').$$ Thus, $\alpha_t$ is a geodesic iff $f'(t)=0\Leftrightarrow t=k\pi+\frac{\pi}{2},\ k\in \mathbb{Z}$. Therefore you obtain that the only parallels which are also geodesics are $$\alpha_{k\pi+\frac{\pi}{2}}(u)=X\left(k\pi+\frac{\pi}{2}, u\right),\ \ k\in \mathbb{Z}.$$


Margem dentro de tabela

Question: Tenho um texto dentro de uma "tabela", porem basicamente queria colocar margem lateral, como um paragrafo.
Maggin, padding, entre outras formas não consegui.
Meu código HTML:

FIFA

Modalidade: Futebol

Jogador por equipe: 01

Tipo de Competição: Melhor de 2 com saldo de gol

Plataforma: PS3, PS4 ou XBOX

Descrição: Sem muito a dizer, os campeonatos de FIFA tem a regras simples e seguimento da competição rígido, mantendo o tradicional mata com saldo de gol, o s jogadores e enfrentam entre si duas vezes onde chegaram ao resultado final.

CSS:
"
#camps{
    width: 100%;
    overflow: hidden;
    margin: 10px auto;
    padding: 30px 0px;
}

#camps ul li{
    list-style: none;
    float: left;
    width: 90%;     /* Comprimento da grade */
    height: 500px;  /* Altura da grade */
    background-color: rgba(10,23,55,0.5);
    margin: 10px 50px 0px 50px;
    box-sizing: border-box;
    border: 1px solid white;

}

    .container ul li{
        float: none;
        width: 30%;
        margin: 40px auto;
    }
}

"
Help plz _
Answer: Deixa eu ver se entendi sua dúvida, você quer assim?

Se for isso, você adiciona no css o codigo abaixo:
.recuo {
    text-indent:2em
}

e dentro do h2 de qualquer texto que desejar é só colocar "class='text-info recuo"

camps{
width: 100%;
overflow: hidden;
margin: 10px auto;
padding: 30px 0px;
}

camps ul li{
list-style: none;
float: left;
width: 90%;     /* Comprimento da grade */
height: 500px;  /* Altura da grade */
background-color: rgba(10,23,55,0.5);
margin: 10px 50px 0px 50px;
box-sizing: border-box;
border: 1px solid white;
}

.container ul li{
    float: none;
    width: 30%;
    margin: 40px auto;
}

.recuo {
text-indent:2em
}

FIFA Modalidade: Futebol Jogador por equipe: 01 Tipo de Competição: Melhor de 2 com saldo de gol Plataforma: PS3, PS4 ou XBOX Descrição: Sem muito a dizer, os campeonatos de FIFA tem a regras simples e seguimento da competição rígido, mantendo o tradicional mata com saldo de gol, o s jogadores e enfrentam entre si duas vezes onde chegaram ao resultado final.

FIFA Modalidade: Futebol Jogador por equipe: 01 Tipo de Competição: Melhor de 2 com saldo de gol Plataforma: PS3, PS4 ou XBOX Descrição: Sem muito a dizer, os campeonatos de FIFA tem a regras simples e seguimento da competição rígido, mantendo o tradicional mata com saldo de gol, o s jogadores e enfrentam entre si duas vezes onde chegaram ao resultado final.

Comment: Preferencialmente use o o **snippet** do editor de texto, assim os usuários que chegarem  questão (e a resposta) poderão observar o código sem a necessidade de ir a outro site.

Margem dentro de tabela


Cardinality of fin of superstructure?

Question: The usual superstructure over $\mathbb R$ is defined as $\mathbb V=\cup_{n<\omega}V_n$ where $V_0=\mathbb R$ and $V_{n+1}=V_n\cup \mathcal{P}(V_n)$. Furthermore let $\mathcal{P}_{fin}(\mathbb V)$ be the set of finite subsets of $\mathbb V$.  Is it correct that the cardinality of both $\mathbb V$ and $\mathcal{P}_{fin}(\mathbb V)$ is $\beth_\omega$ ?
Comment: I really wouldn't use $V$to denote the level-$\omega$ superstructure ...
Comment: Goldblatt in *Lectures on hyperreals* page 164 section 13.6 denotes it $\mathbb U$.  Is that any better?  @NoahSchweber
Comment: Yes, since $U$ doesn't already have a very specific entrenched meaning in set theory.
Comment: Oh, you are referring to von Neumann universe! I had no idea what you were talking about.  What if I switch to $\mathbb V$? @NoahSchweber
Comment: I'd say that's fine too.
Answer: Yes. It is easy to see that $|\mathbb V_n|=\beth_{n+1}$, so $|\mathbb V|=\beth_\omega$, and for every infinite $X$, $\mathcal P_{\rm fin}(X)$ is equipotent to $X$. At least assuming choice, without choice you can still prove this for this specific case, by noting that $\mathbb V$ is equipotent with $V_{\omega+\omega}$ in the sense of the von Neumann hierarchy, and for the von Neumann hirerachy $\mathcal P_{\rm fin}(V_\delta)\subseteq V_\delta$ for all limit $\delta$.

Cardinality of fin of superstructure?


Problems regarding ARMA models and non stationarity

Question: I am struggling to find in easy terms what is the problem regarding nonstationarity of a time series and using  ARMA models on it (excluding "I"). If  we assume that the series is indeed a nonstationary AR(p) process would I get bad results if i just simple fit the time series using a AR(p) model ignoring the nonstationarity ?. Would the fit give bad point estimates or just not trusty variances and other stuff that may impact in prediction intervals for example, since  stationarity does not hold  (and MLE or OLS might need that assumption)? Finally can the model be good regarding its forecast power (withut prediction intervals) ?
Thanks in advance
Comment: It would give bad point estimates, too. You can simulate a trajectory of a nonstationary AR(p) process with known parameter values and fit an AR(p) model. Do that many times and see how the point estimates compare to the true parameter values. I guess point forecasts would also be poor.
Comment: I did simulate some AR(1) and AR(2) processes but I got coeff almost identical to the real ones ( e.g. 1 for  AR(1) with unit root) so I cant see the problem so far
Comment: In the unit root case, for sufficiently long time series, you should be getting coefficients that have the Dickey-Fuller distribution rather than the normal distribution. In the explosive case, that would be something else but again not normal and likely biased.
Comment: Since I am not seeing problems in the point parameters estimates, could I use  such models for forecasting leaving aside the inference, or  if I differentiate I should get better results ? I am struggling mostly because the coefficients seems to be well estimated regardless of the nature of the time series.
Answer: It would give bad point estimates, too. Consequently, point forecasts would also be poor. You can simulate a trajectory of a nonstationary AR(p) process with known parameter values and fit an AR(p) model. Do that many times and see how the point estimates compare to the true parameter values.
Here is a simple simulation showing that point estimates of the slope coefficients in a unit-root AR(1) model (a.k.a. a random walk) are biased (and do not follow a normal distribution asymptotically):
<code>m=1e3 # number of simulations
n=1e3 # length of time series
bhat=rep(NA,m) # for saving estimates of the slope coefficient
for(i in 1:m){
 set.seed(i); eps=rnorm(n)
 x=cumsum(eps)
 bhat[i]=coef(lm(x[-1]~x[-n]))[2]
}
par(mfrow=c(2,1)); plot(density(bhat),main="Density of bhat"); hist(bhat); par(mfrow=c(1,1))
</code>
Comment: This is well known and perhaps boring for many, but I have decided to replicate it here since the OP was apparently not able to obtain the result independently.
Comment: Thanks Richard, I see the bias and non normal dis, in the end if I got it right, I should not fit arma for nonstationarity since  I might get bad estimates and thus bad forecasting capabilities. Do you know a proper book that might help me more into this or explicitly explain the things you are telling me here.
Comment: @tsjm, check out [these threads](https://stats.stackexchange.com/questions/tagged/time-series%2breferences?tab=Votes) for numerous references and pick the one you like.
Comment: Thanks Richard, regarding my question above, and AR model fitted in a non stationary data would lead to bias and non normal distrobution of the coeff, but  leaving inference aside, does it means it wont work for forecast ? I see the non normal distr but the values are super close to one, so it will probably work for forecast,  at least for 1 period ahead
Comment: @tsjm, you can modify my simulation to see that for yourself. Or if I find the time later on, I might do it for you.
Comment: Thanks, I dont use R but I will try to do it on python in the meantime
Comment: @tsjm, unfortunately, I am still too busy to extend the simulation, but perhaps you have got some progress on your own?
Comment: I did simulate some and also found some info about the bias associated with the estimators (even for stationary ARMA models). I just struggle i think to clearly see the fails in the forecasts because when i simulate a stationary and a non stationary process I get similar results regarding forecasts metrics.


Characteristic function on open set is upper-semicontinous

Question: Consider the the open set $A \subset X$ and define on it the characteristic function $$\mathbb{1}_A(x)={ \begin{cases}
1, x \in A\\
\infty, x \not \in A
\end{cases}}$$
Then, the characteristic function $\mathbb{1}_A(x)$ is upper-semicontinous for $x \in A$, as noted in the wikipedia article: https://en.wikipedia.org/wiki/Semi-continuity, i.e. $$lim \sup_{k \to \infty} \mathbb{1} (x_k) \leq \mathbb{1} (x),$$
for some sequence $(x_k)_{k \in \mathbb{N}} \subset X$  with limit $x \in A$ or put differently:
$\mathbb{1}_A(x)$ is upper-semicontinous iff for every real $y > \mathbb{1}_A(x)$ there is a neighborhood $U$ of $x$ such that $y > \mathbb{1}_A(x)$ for all $x_k \in U$.
Conversely for closed sets. Why are those two definitions equivalent in the case of the characteristic function and in general?
Comment: it's a classic argument by contradiction, try by yourself
Answer: Let's break it down. We have two things we want to show are equivalent. Fix $A$ and let $\chi_A$ be the characteristic function for $A$.

For any sequence $(x_k) \subseteq X$ with $\lim_{k \rightarrow \infty} x_k = x \in A$, we have
$$\limsup_{k \rightarrow \infty} \chi_A (x_k) \leq \chi_A(x).$$

For every real $y > \chi_A(x)$ there is a neighborhood $U$ of $x$ so that $y > \chi_A(x_k)$ for every $x_k \in U$.

Let's show $1) \implies 2)$. Let $y > \chi_A(x)$. Per your definition, this can only happen if $x \in A$. Suppose that for every neighborhood $U$ of $x$ we can find $x_k \in U$ so that $y \leq \chi_A(x_k)$. Then by 1) we see that
$$y \leq \limsup_{k \rightarrow \infty} \chi_A(x_k) \leq \chi_A(x),$$
a contradiction.
Let's show $2) \implies 1)$. Suppose we have a sequence $x_k \rightarrow x \in A$ such that $\limsup_{k \rightarrow \infty} \chi_A(x_k) > \chi_A(x)$. Let $y := \limsup_{k \rightarrow \infty} \chi_A(x_k)$. Then by 2), we see that we can find a neighborhood $U$ of $x$ so that $y > \chi_A(x_k)$ for every $x_k \in U$. Since $x_k \rightarrow x$, we have that $x_k$ is in $U$ for sufficiently large $k$, but this is a contradiction to our limsup assumption.


How to detect which one is the better study when they give you conflicting results?

Question: You so often come across in the press various studies that conclude directionally opposite results.  Those can be related to the testing of a new prescription drug or the merit of a specific nutrient or anything else for that matter.
When two such studies arrive at conflicting results how can you tell which one of the two is closest to the truth?
Comment: @whuber I would vote against CW because even if there are different perspectives there is likely to be one *best* approach. This is similar to how the same hypothesis can be tested using different frameworks/models but there is likely to be one best approach.
Comment: Maybe this should be CW?  There will not be a unique answer to this question and multiple perspectives and approaches might emerge.
Comment: @Srikant: In any particular case I can imagine you could amass a strong defense to support your assertion.  In general, though--which is the present situation--the best answer will depend on the context.  As a simple (and incomplete) example, contemplate the differences between evaluating a pair of designed physical experiments (such as measuring the speed of light, where historically most of the confidence intervals have missed the truth!) and an observational study in the social sciences.
Comment: @whuber Perhaps, we should continue this conversation on meta. I admit that I am still fuzzy about when to use CW and when not to but to take up your point: the very best answer to this question would then be that the answer is context dependent and explain why via a few examples. In any case, I somehow feel that this question should not be CW but I am unable to articulate any more reasons beyond the ones I have outlined above.
Answer: The meta analysis literature is relevant to your question. Using meta-analytic techniques you could generate an estimate of the effect of interest pooled across studies. Such techniques often weight studies in terms of their sample size.
Within the meta analysis context researchers talk about fixed effect and random effect models (see Hunter and Schmidt, 2002). A fixed effect model assumes that all studies are estimating the same population effect. A random-effects model assumes that studies differ in the population effect that is being estimated. A random-effects model is typically more appropriate.
As more studies accumulate looking at a particular relationship, more sophisticated approaches become possible. For example, you can code studies in terms of various properties, such as perceived quality, and then examine empirically whether the effect size varies with these study characteristics. Beyond quality there may be some theoretically relevant differences between the studies which would moderate the relationship (e.g., characteristic of the sample, dosage levels, etc.).
In general, I tend to trust studies with:

bigger sample sizes
greater methodological rigour
a confirmatory orientation (e.g., not a study where they tested for correlations between 100 different nutrients and 50 health outcomes)
absence of conflict of interest (e.g., not by a company with a commercial interest in showing a relationship; not by a researcher who has an incentive to find a significant result)

But that said you need to keep random sampling and theoretically meaningful differences between studies as a plausible explanation of conflicting study findings.
Comment: I particularly like the likelihood ratio as a means of aggregating evidence in meta-analysis; if you have sufficient data to compute them for each study, you simply compute the product across studies to represent the aggregate evidence for/against a hypothesis.
Comment: I commented on the (ir)relevance of meta analysis after Cyrus's answer, but upvoted this response for everything else, especially the bullet points.
Comment: @whuber @Gaetan's question assumes that one study is closer to the truth. I try to take a step back and situate variations in results between studies within a meta-analytic framework, acknowledging the possibility that the studies may be of equal quality, but that random sampling or substantive differences may be the explanation.
Comment: @whuber Even with two-studies it would be possible to form a meta-analytic estimate of the effect of interest. Of course, the confidence interval of the estimate of effect may be large. But a high degree of uncertainty is to be expected if only two studies have been conducted and they are giving conflicting results.
Answer: I would hold off on considering meta-analysis until you've scrutinized sources if potential bias or variation in the target populations. If these are studies of treatment effects, was treatment randomly assigned? Were there deviations from the protocol? Was there noncompliance? Is there missing outcome data? Were the samples drawn from the same frame? Was there refusal to participate? Implementation errors?  Were standard errors computed correctly, accounting for clustering and robust to various parametric assumptions? Only after you have answered these questions do I think meta-analysis issues start to enter the picture.  It must be rare that for any two studies meta-analysis is appropriate, unless you are willing to make sone heroic assumptions.
Comment: @chl: True, but the point is that these steps get to the essence of the question.  A meta-analysis would be helpful only when there are many studies (not just two) and their merits have already been carefully evaluated.  The question before us is really asking how one goes about evaluating the quality of a study, or pair of conflicting studies, in the first place.  Cyrus has pointed to some of the many aspects of this; a reasonable treatment usually requires one or two semesters of university-level study.  In this light I think his use of the term "heroic" is somewhat understated!
Comment: @whuber Yes, I agree with you and @Cyrus. Of course, assessing the quality and trustiness of previous studies is a mandatory step (and it takes time to review every studies, especially when we have to contact authors because informations are missing in the MS); I just thought this was part of the meta-analysis, and the "statistical part" reduces to bringing a quantitative summary of trustworthy results.
Comment: But aren't these steps already part of meta-analysis?
Answer: I think Jeromy's answer is sufficient if you are examining two experimental studies or an actual meta-analysis. But often times we are faced with examining two non-experimental studies, and are tasked with assessing the validity of those two disparate findings.
As Cyrus's grocery list of questions suggests, the topic itself is not amenable to short response, and whole books are in essence aimed to address such a question. For anyone interested in conducting research on non-experimental data, I would highly suggest you read
Experimental and quasi-experimental designs for generalized causal inference by William R. Shadish, Thomas D. Cook, Donald Thomas Campbell (Also I have heard that the older versions of this text are just as good).
Several items Jeromy referred to (bigger sample sizes, and greater methodological rigour), and everything that Cyrus mentions would be considered what Campbell and Cook refer to as "Internal Validity". These include aspects of the research design and the statistical methods used to assess the relationship between X and Y. In particular as critics we are concerned about aspects of either that could bias the results, and diminish the reliability of the findings. As this is a forum devoted to statistical analysis, much of the answers are centered around statistical methods to ensure unbiased estimates of whatever relationship you are assessing. But their are other aspects of the research design unrelated to statistical analysis that diminish the validity of the findings no matter what rigourous lengths one goes to in their statistical analysis (such as Cyrus's mention of several aspects of experiment fidelity can be addressed but not solved with statistical methods, and if they occur will always diminish the validity of the studies results). There are many other aspects of internal validity that become crucial to assess in comparing results of non-experimental studies that are not mentioned here, and aspects of research designs that can distinguish reliability of findings. I don't think it is quite appropriate to go into too much detail here, but I would often take the results of a quasi-experimental study (such as an interrupted time series or a matched case-control) more seriously than I would a study that is not quasi experimental, regardless of the other aspects Jeromy or Cyrus mentioned (of course within some reason).
Campbell and Cook also refer to the "external validity" of studies. This aspect of research design is often much smaller in scope, and does not deserve as much attention as internal validity. External validity essentially deals with the generalizability of the findings, and I would say laymen can often assess external validity reasonably well as long as they are familiar with the subject. Long story short read Shadish's, Cook's and Campbell's book.


Is the call order guaranteed for multiple SetWindowSubclass against the same window?

Question: I am using SetWindowSubclass to set up two different subclass procedures against a control (in this case, a multiline edit field).
One subclass "edit" functionality specific to edit controls and the other "base" functionality specific to any control. It seems that no matter what order I apply these in "base" is being called before "edit".
Has anyone else hit this issue?
Comment: How is the API to know which window procedure you deem "base" and therefore always call that first?
Comment: Hi Cody - my understanding is that the most recently added subclass is called first, going backwards to the first subclass. However, the docs on MSDN say nothing on this. I may end up just having a single level of subclassing and have each control-specifc class call the 'base' logic itself. Gotta love win32. :)
Comment: I couldn't dig up any information about this. As you say, the logical behavior would be last subclassed is the outer one. This blog post hints at just zthis happening: http://blogs.msdn.com/b/oldnewthing/archive/2003/11/11/55653.aspx
Comment: Hi Peter - thanks for your input. Looks like it's time for me to pester Raymond Chen at next PDC. He has helped me with other murky win32 issues.
Answer: There is no guarantee of order, sorry.


Action Filters in WCF Services

Question: Is there something Like ActionFilterAttribute (From ASP.NET MVC) in WCF Services (Or anything like that). basically what I want to do is to log what is coming and goint to and from my services, and I don't want to write the logging code in every single ServiceContracts. yes the question is very general but you understand the idea what I want to do.
Comment: possible duplicate of [WCF service attribute to log method calls and exceptions](http://stackoverflow.com/questions/13655541/wcf-service-attribute-to-log-method-calls-and-exceptions)
Answer: Yes there is it called as MessageInspectors/ParameterInspectors , here you can read about them
http://msdn.microsoft.com/en-us/library/aa717047%28v=vs.110%29.aspx
This is exactly what you are looking for , WCF custom behavior log logging
http://www.codeproject.com/Articles/243352/LoggingBehavior-How-to-Connect-Log-prints-with-the
Only confusing thing is you can have message inspector on WCF service and WCF proxy as well , in your case you need only for service side
Answer: I had to read a lot to find this out, I'm not an expert in WCF but given this information is a little scarce I'm sharing what have worked for me.
My Solution consists of using an OperationBehavior and a DispatcherMessageInspector
OperationBehavior

Allows you to change the binding information, validate de operation
description, and apply dispatcher behaviors.

DispatcherMessageInspector

Allows you to inspect and change the messages that are sent for your
service.

Dispatcher

Gets the messages from the communication channels and sends to the
right operation, and get the result back to the caller.

Service Operation

are your service methods

CODE SOLUTION
MESSAGE INSPECTOR
   public class MyMessageInspector : IDispatchMessageInspector
    {
        List<string> targetOperations = new List<string>();

        public MyMessageInspector(OperationDescription operation)
        {
            this.AddOperation(operation);
        }

        public void AddOperation(OperationDescription operation)
        {
            this.targetOperations.Add(operation.Messages[0].Action);
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (TargetOperationMatchesRequest(request))
            {
                request = ChangeMessage(request);

                return true;
            }else
            {
                return false;
            }
        }

        public bool TargetOperationMatchesRequest(Message request)
        {
            string requestAction = request.Headers.To.AbsolutePath;
            requestAction =  requestAction.Substring(requestAction.LastIndexOf("/"));

            string targetOperation = "";
            foreach (string targetOperationPath in targetOperations)
            {
                targetOperation = targetOperationPath.Substring(targetOperationPath.LastIndexOf("/"));
                if (targetOperation.Equals(requestAction))
                {
                    return true;
                }
            }
            return false;
        }

        public Message ChangeMessage(Message oldMessage)
        {
            Message newMessage = request.CreateBufferedCopy(Int32.MaxValue).CreateMessage();
            //Change your message

            return newMessage;

        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }
    }

OPERATION
public class MyOperation : Attribute, IOperationBehavior
    {
        public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
        {
        }

        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {

            MyMessageInspector inspector = dispatchOperation.Parent.MessageInspectors
                .Where(x => x is MyMessageInspector)
                .FirstOrDefault() as MyMessageInspector;

            if (inspector != null)
            {
                inspector.AddOperation(operationDescription);
            }
            else
            {
                inspector = new MessageInspectors(operationDescription);
                dispatchOperation.Parent.MessageInspectors.Add(inspector);
            }
        }

        public void Validate(OperationDescription operationDescription)
        {
        }
    }

CONTRACT
[ServiceContract]
public interface IService
{
    [OperationContract]
    [MyOperation]
    OutputData MyMethod(InputData inputData);
}

SERVICE
    public class Service : IService
    {
            [WebInvoke(Method = "POST", UriTemplate = "/json/MyMethod", RequestFormat = WebMessageFormat.Json,  ResponseFormat = WebMessageFormat.Json)]
            public OutputData MyMethod(InputData inputData)
            {
               //Implementation
               return new OutputData();

            }
    }

Action Filters in WCF Services


Sum of a diagonal matrix and a symmetric positive semidefinite matrix

Question: Let the following symmetric matrix
$A = \left[ \matrix{a_{12}+a_{13} &    -a_{12}    &    -a_{13}    \\
                      -a_{12}     & a_{12}+a_{23} &    -a_{23}    \\
                      -a_{13}     &    -a_{23}    & a_{13}+a_{23} } \right]$,
where each $a_{ij}$ is a nonnegative real number, and hence, $A$ is a symmetric positive semidefinite matrix, because:
$
x^T A x = (a_{12}+a_{13}) x_{1}^2 +
          (a_{12}+a_{23}) x_{2}^2 +
          (a_{13}+a_{23}) x_{3}^2
- 2( a_{12} x_1 x_2 + a_{13} x_1 x_3 + a_{23} x_2 x_3 ) \\
= a_{12}(x_1 - x_2)^2 + a_{13}(x_1 - x_3)^2 + a_{23}(x_2 - x_3)^2 \geq 0 $
On the other hand:
Let $B = A + D =
         \left[ \matrix{a_{12}+a_{13} &    -a_{12}    &    -a_{13}    \\
                          -a_{12}     & a_{12}+a_{23} &    -a_{23}    \\
                          -a_{13}     &    -a_{23}    & a_{13}+a_{23} } \right] +
         \left[ \matrix{d_{11} &        &         \\
                               & d_{22} &         \\
                               &        & d_{33}  } \right]$,
where $d_{ii} \in \mathbb{R}$, that is, $D$ is a diagonal matrix with positive and negative real numbers.
What are the limits of $d_{ii}$ so that B is still a positive semidefinite matrix?
Comment: What is $\mathbb R^+$? Does it contain nonnegative real numbers or only positive real numbers?
Comment: I am sorry. Nonnegative real numbers. I will modify it.
Comment: The problem arises from an electrical engineering question. Where the matrix $ A $ is the reactance matrix of the system, and $ B $ represents values of capacitors and reactances of lines connected to a substation.
Answer: By Sylvester's criterion, $A+D$ is positive semidefinite if and only if all principal minors of $A+D$ are nonnegative. In other words, $A+D$ is PSD iff
\begin{aligned}
&d_1+a_{12}+a_{13}\ge0,\\
&d_2+a_{12}+a_{23}\ge0,\\
&d_3+a_{13}+a_{23}\ge0,\\
&(d_1+a_{12}+a_{13})(d_2+a_{12}+a_{23})\ge a_{12}^2,\\
&(d_1+a_{12}+a_{13})(d_3+a_{13}+a_{23})\ge a_{13}^2,\\
&(d_2+a_{12}+a_{23})(d_3+a_{13}+a_{23})\ge a_{23}^2\\
\end{aligned}
and
\begin{aligned}
&(d_1+a_{12}+a_{13})(d_2+a_{12}+a_{23})(d_3+a_{13}+a_{23})\\
-&a_{23}^2(d_1+a_{12}+a_{13})
-a_{13}^2(d_2+a_{12}+a_{23})
-a_{12}^2(d_3+a_{13}+a_{23})
-2a_{12}a_{13}a_{23}
\ge0.
\end{aligned}
The region bounded by these surfaces is typically not a translated octant of $\mathbb R^3_+$. Therefore, we cannot find a vector $(d_1',d_2',d_3')$ such that $A+D$ is positive semidefinite if and only if $(d_1,d_2,d_3)\ge(d_1',d_2',d_3')$.
To illustrate, consider the analogous case where $A$ is $2\times2$. If $A$ is nonzero, by scaling $A$, we may assume that
$$
A=\pmatrix{1&-1\\ -1&1}.
$$
In this case, if $D=\operatorname{diag}(d_1,d_2)$, then $A+D$ is positive semidefinite if and only if $d_1+1\ge0,\ d_2+1\ge0$ and $(d_1+1)(d_2+1)\ge1$. That is, the feasible region of $(d_1,d_2)$ is the region above the upper right branch of the hyperbola $(d_1+1)(d_2+1)\ge1$. The hyperbola simply hasn't any "bottom left corner" $(d_1',d_2')$ that is entrywise less than or equal to all $(d_1,d_2)$ in the feasible region.
Comment: you are right. $A$ is a positive semidefinite matrix. I will modify the question
Comment: I have modified the question. Please can you see it?
Comment: if $d_{1}, d_{2}, d_{3} > 0$, then $e^{T}De>0$.  You seem to be assuming that the diagonal entries in $D$ are all negative, but why do you make that assumption?
Comment: @BrianBorchers The OP has changed the question. $d$ was $\le0$ in the original question.
Comment: Thank you very much for your good explanation. Is it possible to extend this for dimensions greater than 3? That is, is it possible to express the determinant in an easy way? Or define conservative limits in a simpler way?
Comment: @JonattanSarmiento In theory $\det(A+D)=\sum_{r=0}^n\sum_{|I|=r}\det D[I,I]\det A(I,I)$, where $I\subseteq\{1,2,\ldots,n\}$ denotes an index set of size $r$, $D[I,I]$ is the principal submatrix indexed by $I$ and $A(I,I)$ is the principal submatrix obtained by deleting the rows and columns indexed by $I$. The principal minors of $A+D$ can be calculated in a similar manner. However, unless $n$ is small, this really isn't quite practical.
Answer: Note that $A$ is positive semidefinite is not positive definite. In other words, $A$ is positive semidefinite and singular.
First, note that if all three $d_{ii}$ are positive, then $A + D$ will necessarily fail to be positive semidefinite.
So, we must suppose that at least on of these is zero. Without loss of generality, suppose that $d_{33} = 0$. If both $d_{11},d_{22}$ are non-zero, then we find that $A + D$ can only be positive semidefinite if $A$ is diagonal with $a_{33} = 0$. In this case, this only occurs when $A = 0$.
For the remaining case, we must suppose that one of $d_{11},d_{22}$ are zero. Without loss of generality, suppose that $d_{22} = 0$. In other words, we are looking for the maximal value of $d_{11}$ for which
$$
A - \pmatrix{d_{11} & 0 & 0\\0 &0 &0\\0 &0&0}
$$
is positive semidefinite. As is shown here, for instance, this matrix will be positive definite for $d_{11} \leq 1/A^+_{11}$, where $A^+_{11}$ denotes the $1,1$ entry of the Moore-Penrose pseudoinverse $A^+$ of $A$.

As we established above, it is sufficient to consider the case in which at most one of the $d_{ii}$ are non-zero, since $A + D$ will fail to be positive semidefinite otherwise. We compute (via matlab)
$$
A^+ = \left(\begin{array}{ccc} \frac{4\,b_{1}+b_{2}+b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & -\frac{2\,b_{1}+2\,b_{2}-b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & -\frac{2\,b_{1}-b_{2}+2\,b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)}\\ -\frac{2\,b_{1}+2\,b_{2}-b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & \frac{b_{1}+4\,b_{2}+b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & -\frac{2\,b_{2}-b_{1}+2\,b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)}\\ -\frac{2\,b_{1}-b_{2}+2\,b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & -\frac{2\,b_{2}-b_{1}+2\,b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} & \frac{b_{1}+b_{2}+4\,b_{3}}{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)} \end{array}\right)
\\ =
\frac{1}{9(b_1b_2 + b_1 b_3 + b_2 b_3)}\sum_{i=1}^3b_i\,(-2e_i + e_{i+1} + e_{i+2})(-2e_i + e_{i+1} + e_{i+2})^T,
$$
where in the above we take $b_{1} = a_{23}, b_2 = a_{13},b_3 = a_{12}$.  In the second line, $e_i$ denotes the $i$th standard basis vector and addition in the indices is modulo $3$.
We see then, for instance, that the maximal $d_{11}$ for which $A + D$ is positive semidefinite is given by
$$
d_{11} = \frac{9\,\left(b_{1}\,b_{2}+b_{1}\,b_{3}+b_{2}\,b_{3}\right)}{4\,b_{1}+b_{2}+b_{3}}.
$$
Similar conditions hold for $d_{22},d_{33}$.
Comment: Thank you very much. I have added the following information, which may be useful...

$A$ is a symmetric positive semidefinite matrix, because:

$
x^T A x = (a_{12}+a_{13}) x_{1}^2 +
                (a_{12}+a_{23}) x_{2}^2 +
                (a_{13}+a_{23}) x_{3}^2 - 2( a_{12} x_1 x_2 + a_{13} x_1 x_3 + a_{23} x_2 x_3 ) \\
= a_{12}(x_1 - x_2)^2 + a_{13}(x_1 - x_3)^2 + a_{23}(x_2 - x_3)^2 \geq 0 $
Comment: @Jon See my latest edit
Comment: Thanks! I have modified the question. Please can you see it?
Comment: If the entries in $D$ are all positive, then $A+D$ will still be positive semidefinite, since $x^{T}(A+D)x \geq 0$ for all $x$.
Comment: You're right. But, if $ D $ can have positive and negative values, what is the condition for $ B $ to be positive semi-defined?


Softmax regression: Intuition about why distribution of $y$ is in terms of $e^{\theta^Tx}$ as opposed to just $\theta^Tx$

Question: I'm going through Andrew Ng's lecture notes on Machine Learning and I just learnt about softmax regression there.
We see that, for softmax regression, the conditional distribution of $y$ given $x$ is given as:
This formula contains terms of form $e^{\theta^Tx}$. I was just wondering if there is an intuitive explanation for this? Or, why isn't the derived formula for probability simpler like:
$$\frac{\theta^Tx}{\sum_j\theta_{j}^Tx}$$
And is there an intuitive explanation for what that would mean?
Answer: You need power to get rid of negative values. When you raise positive number to the power - you will always get positive value. For negative power - the result is just small and for positive - it's big and grows exponentially.
By using softmax you will never get negative probability nor probability higher then 1 and will never divide by zero when calculating it
$$\frac{ e^{\Theta_{i}^T x }}{ \sum_{j}  e^{\Theta_{j}^T x } }$$
Comment: It makes taking derivative simpler.
Comment: And why using `e` instead of arbitary number > 1?
Answer: There is an intuitive definition.  I tried to explain the softmax in this answer.  To put it simply, you are interpreting the unbounded $\theta_i^Tx$ as log-odds, and the softmax converts them to probabilities in $[0,1]$.  Your formula has no such interpretation.


Mouseover in map loop reactjs

Question: How to set hover for itself within map in Reactjs
  hoverOn = () => {
    this.setState({ hover: true});
  }
  hoverOff = () => {
    this.setState({ hover: false });
  }

    ...
    var components = posts.map((post, i) => (
    .....
         this.viewPost(post, e)}>
    ......
    ));

Since I use setState, everytime I hover on span it reflects to all list data which returned from map loop.
How can I use hover to reflect on itself element?
Thank so much
Answer: You can make hover inside state an object state = { hover: {} } and set it with index i on events i.e. this.setState({ hover: {...this.state.hover, i: true }});.
Then pass i parameter into those methodsonHover={(i) => this.hoverOn(i)}
And change className setup to <span className={this.state.hover[i] ? 'showtooltip':'hidetooltip'} (thanks to @kenny for noticing this)
Comment: And your element should be `<span className={this.state.hover[i] ? 'showtooltip':'hidetooltip'} .....`
Comment: make a new obj like `var dupHover = this.state.hover` and then `dupHover[i] = true` and finally `this.setState({hover: dupHover})`
Comment: @Kenny, @hai-tien, sorry, yes I just edited it, you can set state like this:  `this.setState({ hover: {...this.state.hover, i: true }});` - generic approach I think. I guess you can't hover more than one element at a time, so it could be just a new object with `{i: true}`
Comment: This line `this.setState({ hover[i]: true });` show wrong syntax although I added to state `hover: {}`
Answer: wrap this logic in a little Component:
class Foo extends React.Component {
  constructor(){
    this.state = { hover: false };
  }

  render(){
    return  this.setState({ hover: true }) }
      onMouseOut={ () => this.setState({ hover: false }) }
    />;
  }
}

and use that Component:
...
var components = posts.map((post, i) => (
.....
    <Foo onClick={(e) => this.viewPost(post, e)}></Foo>
......
));

Comment: Makes more sense
Comment: @Thomas. Thanks. It works well but I do not know why we need to add ...this.props in return?
Comment: @HaiTien because you add an `onClick` handler to the component, and you add `children` to the component. If you don't forward these properties from the `` to the `` then the span will be rendered empty and without click-handler

Mouseover in map loop reactjs


Extension to Witt's bases

Question: Let $X$ be a real finite dimensional linear space. Let $B:X\times X \rightarrow \mathbf{R}$ be a bilinear symmetric non-degenerated form. Let $M$, $N$ be totally isotropic subspaces with the same dimension $r$ such that $M\cap N=\{0\}$.
Assume that $e_1, ...,e_s$ are linearly indedendent in $M$, $f_1,...,f_s$ are linearly independent in $N$ (where $s< r$) and $B(e_i,f_j)=\delta_{i,j}$ for $i,j=1,...,s$.
Is it possible to extend $e_1,...,e_s$ to a basis $e_1,...,e_r$ in $M$, $f_1,...,f_s$ to a basis $f_1,...,f_r$ in $N$  in such a way that $B(e_i,f_j)=\delta_{i,j}$ for $i,j=1,...,r$?
I know only that for each basis $e_1,...,e_r$ in $M$ there exists a basis $f_1,...,f_r$ in $N$ such that $B(e_i,f_j)=\delta_{i,j}$ for $i,j=1,...,r$ (Bourbaki, Algebra, Chap.11, $\S$4,2, Prop.2)
Thanks.
Answer: I think you need some additional assumption such as $X = M \oplus N$.
For example, if $s=0$, you're just asking whether any 2 totally isotropic subspaces with intersection $\{0\}$ have bases satisfying $B(e_i, f_j) = \delta_{i,j}$, and this will be false if you take some totally isotropic subspace $U = \langle e_1, e_2 \rangle $ and split it into $M = \langle e_1 \rangle$ and $N = \langle e_2 \rangle$.  The whole space could still be big enough to be nondegenerate.
If you assume $X = M \oplus N$ (so $X$ has dimension $n=2r$), you can do it.  It suffices to show how to do a single step from $s$ to $s+1$.  Let $M_s$ be the span of $e_1, \ldots, e_s$ and let $N_s$ be the span of $f_1, \ldots, f_s$.  Pick some $e = e_{s+1}$ not in $M_s$.  By nondegeneracy (and the assumption $X = M \oplus N$), $N \cap e^\perp$ is a proper subspace of $N$.  Therefore there exists a vector in $N$ outside both $N \cap e^\perp$ and $N_s$ (the union of two proper subspaces of $N$ cannot be all of $N$). Choose such a vector and make it $f_{s+1}$; by construction, it lies in $N$, and $B(e_{s+1}, f_{s+1})$ is nonzero and therefore we can scale $f_{s+1}$ to make the inner product equal to  1.
Comment: The following almost works.  After doing the above argument, Write $e'_{s+1} = \sum c_i e_i$ and $f'_{s+1} = \sum d_i e_i$ summing over $i=1, \ldots, s+1$.  If we set $B(e_i, f'_{s+1}) = 0$ and $B(f_i, e'_{s+1})=0$ for $i = 1, \ldots, s$, then we conclude $c_i = -c_{s+1} B(e_{s+1}, f_i)$ and $d_i = -d_{s+1} B(f_{s+1}, e_i)$.  The only problem is to make $B(e'_{s+1}, f'_{s+1}) = c_{s+1} d_{s+1} \sum_i B(e_{s+1}, f_i) B(f_{s+1}, e_i)$ nonzero.  Unless that last sum is 0, we're done.  And it would have to be 0 for all choices of $e_{s+1}$ and $f_{s+1}$ for a counterexample...
Comment: Thanks. Could you write  yet why $B(e_i,f_{s+1})=0$ for $i=1,...,s$.

Extension to Witt's bases


Adding items to an Arraylist

Question: So i am trying to add items to an arraylist, However when I try to write the add method the IDE gives me an error that I'm passing "name, cusip and ticker wrong. Can someone explain to me what I am doing wrong here? Thank you in advance.
Here is my ETF class
package fundProject;

import java.util.Scanner;

public class ETF extends AbstractETF {
    private String name;
    private int cusip;
    private int ticker;

    public ETF(String name, int cusip, int ticker) {
        this.name = getName();
        this.cusip = getCusip();
        this.ticker = getTicker();

    }

    public int getCusip() {
        System.out.println("Please enter the Cusip of the ETF");
        Scanner sc = new Scanner(System.in);
        cusip = sc.nextInt();
        return cusip;
    }

    public int getTicker() {
        System.out.println("Please enter the Ticker of the ETF");
        Scanner sc = new Scanner(System.in);
        ticker = sc.nextInt();
        return ticker;
    }

    public String getName() {
        System.out.println("Please enter the Name  of the ETF");
        Scanner sc = new Scanner(System.in);
        name = sc.next();
        return name;

    }
}

And here is my main class
package fundProject;

import java.util.ArrayList;

public class mainClass {

    public static void main(String[] args) {

        ArrayList<ETF> etfArrayList = new ArrayList<ETF>();

        etfArrayList.add(new ETF(name, cusip, ticker));
        }
    }

Comment: Where are name, cusip, and ticker declared?
Comment: ^^^ @RobertMoskal is right, you need those values declared, and they need to BE something, they need a value or they are useless. You didnt think this through mate, research and attempt to debug before you post a question. Just a solid tip. After reading through the answers, i suggest you delete this question as it does not help the community and should not have been posted in the first place.
Comment: Your `ETF` class is very confusing. First it calls [overrideable method from a constructor](http://stackoverflow.com/a/3404369/2071828). Then, whenever anyone tries to use the [accessors](http://java.about.com/od/workingwithobjects/a/accessormutator.htm) for its variables, the thing tries to read a new value from a `Scanner`! I would seriously rethink your design. Also [**always close your resources**](http://download.java.net/jdk7/archive/b131/docs/technotes/guides/language/try-with-resources.html).
Answer: It's because you're not defining what exactly name cusip and ticker are. You should declare them somewhere first.
Example:
public static void main(String[] args) {

    ArrayList<ETF> etfArrayList = new ArrayList<ETF>();
    String name = "John Doe";
    int cusip = 1;
    int ticker = 1;

    etfArrayList.add(new ETF(name, cusip, ticker));
    }
}

You also need to rewrite your constructor for those arguments to be accepted:
public ETF(String name, int cusip, int ticker) {
    this.name = name;
    this.cusip = cusip;
    this.ticker = ticker;
}

Overall your ETF class could use another look-over. It's not easy to understand.
Answer: First, you haven't defined the variables name, cusip, and ticker in the mainClass class, so the compiler generates an error here.
However, you don't even use those 3 parameters in your ETF constructor.
I would do one of the following things:

Eliminate the parameters to the constructor, and don't pass anything into the constructor.
Or, move the code to ask the user for input to main, so you can pass those variables into the constructor.  The constructor would simply copy the values.

Adding items to an Arraylist


How to databind a property on a custom user control?

Question: I have a custom user control UserProfileLink on which I have two basic string properties, UID and UserFullName which I would like to use in a template column in a DataGrid like this:
....
<ItemTemplate>
  <td:UserProfileLink ID="uplUser" runat="server" UID="<%#Eval("UserUID") %>" UserFullName="<%#Eval("UserFullName") %>" />
</ItemTemplate>
....

I get an error saying "The server tag is not well formed" which leads me to believe this type of binding isn't possible. Is there a way to do this, or is it impossible?
Answer: Try ' instead of " for the server tag
<td:UserProfileLink ID="uplUser" runat="server" UID='<%#Eval("UserUID") %>' UserFullName='<%#Eval("UserFullName") %>' />


Degree of an interesection divisor

Question: Let $\mathcal{C},\Gamma\subseteq \mathbb{P}^2(\mathbb{C})$ be two smooth algebraic curves defined by:
$$\mathcal{C}:F(X_0,X_1,X_2)=0 \ \ \ \ \ \ \Gamma:G(X_0,X_1,X_2)=0$$
such that none of them contains the other one. We already know that $\mathcal{C}$ can be canonically equipped with a compact Riemann surface structure. We've defined the intersection divisor of $\Gamma$ with $\mathcal{C}$ as:
$$\Gamma\cdot \mathcal{C}:=\sum_{p\in\mathcal{C}} I(p)p$$
where:
$$I(p):=\nu_p\left(\frac{G}{H}\right)$$
where $H=H(X_0,X_1,X_2)$ is an homogenous polynomial of degree $\deg(G)$ that doesn't vanish in $p$ (this definition doesn't depend on the choice of $H$ and it's meaningful since $G/H$ is a meromorphic function of $\mathcal{C}$).
Now I'd like to prove that:
$$\deg(\Gamma\cdot \mathcal{C})=\deg(G)\deg(F)$$
The book that I'm using proves this when
$$G(X_0,X_1,X_2)=X_1^m$$
and then states that this is not a loss of generality. Why is it so? Why is it sufficient to prove this statement just for monomials?
Comment: @Kadinskji - the answer to your question depends on the contents of the book - which book is it?
Comment: @hm2020 it's my professor's note (they are written in Italian).
Comment: The theorem is the "Bezout theorem" and you will find many books giving an elementary exposition of this result. Here is a link to one http://www.math.lsa.umich.edu/~wfulton/CurveBook.pdf
Answer: That's the way the geometers of the old Italian school proved Bezout's Theorem.
The basic idea is that you can deform the curve of degree $m$ to make it become $m$ copies of a line, and in fact the $X_1=0$ line up to a change of coordinates (concretely, deforming a curve means changing the coefficients of its equation in a continous way). One then notices that as the curve is deformed the intersection points vary continously as well, thus the degree of the intersection divisor won't change.
Of course this approach needs some finer formalization since it is not entirely obvious that this deformation can be done in such a way at every step except the final the curve remains smooth (this is possibly irrelevant) and also that when intersection points collide the index $I(P)$ behaves as one would expect.
Comment: Do you know any reference that formalizes this approach?
Comment: @Kandinskij : I learned  Bezout's Theorem reading Walker's book on curves but it was a long time ago and I cannot recall if he follows this idea or if the approach is different. He certainly uses Commutative Algebra which is the correct tool to prove these kind of things in Algebraic Geometry. In fact the Old Italian Schhol died out since they couldn't accept the lack of rigour critics and never accepted Commutative Algebra (which was brought into the subject by Zariski).

Degree of an interesection divisor