Dynamically allocating a matrix using unique pointers

Question: The exercise I'm trying to solve states that I should create a dynamically allocated matrix using unique pointers that permits the following operations:

Matrix a,b;
Matrix c(b);
Matrix d=a;
Matrix e= a + b;

So far I've tried implementing the matrix (excluding the addition) but I can't wrap my head around how I should implement unique pointers in this example.

class Matrix
{

public:
    vector<vector<int>> data;

    Matrix() {}

    Matrix(vector<vector<int>> matrix)
    {
        this->data=matrix;
    }

    Matrix (const Matrix& m2)
    {
        this->data=m2.data;

    }
    Matrix& operator= (const Matrix &m2)
    {
        this->data = m2.data;
        return *this;
    }

  void print()
    {
        vector< vector<int> >::iterator row;
        vector<int>::iterator col;
        for (row = data.begin(); row != data.end(); row++)
        {
            for (col = row->begin(); col != row->end(); col++)
            {
                cout<<*col<<" ";
            }
            cout<<endl;
        }
    }

} ;

int main()
{
    vector<vector<int> > matrix(3);
    for ( int i = 0 ; i < 3 ; i++ )
        matrix[i].resize(3);

    Matrix m(matrix);
    m.print();

    Matrix m2(m);
    m2.print();

    Matrix m3;
    m3=m2;
    m3.print();

}

Help is much appreciated. Cheers.
Comment: Your assignment specifies unique pointers, but you are using vectors. This is most probably not what your instructor wants.
Comment: Square matrix? For a matrix of size `n`, just allocate `n*n` integers and store them in a unique_ptr. I.e. `data = std::make_unique(n*n);`. You will also have to store the size, `size = n`. That goes in your main constructor, implement all the other operations from there.
Comment: I'm not sure what you mean. Do you want to store the _data_ in a `unique_ptr` (If yes, why? `vector` seems to be better suited.) Or do you want to create unique_ptrs to `Matrix`, e.g. `std::unique_ptr`? If yes, please show us an example of what you tried and what failed.
Answer: The only practical problem with you solution is that you user a vector of vectors, which may be slightly inefficient because there's an extra level of indirection in accessing the inner vector.
Better is to allocate a single vector to store the whole matrix, so:
class Matrix
{
public:
    vector<int> data;
    int width;

    Matrix(int w, int h) : data (w * h), width(w)
    {

    }

    int& elementAt(int x, int y)
    {
        // Offset the row with y * width, then in the row the xth element
        return data[y * width + x];
    }

    ...

Instead of a vector you could just allocate a block of memory, managing it in a unique_ptr::
class Matrix
{
public:
    unique_ptr<int[]> data;
    int width;

    Matrix(int w, int h)
     : data (new int[w * h]), width(w) // Allocate dynamic array in unique_ptr
    {
       // Initialize data to zero
    }

    int& elementAt(int x, int y)
    {
        // Offset the row with y * width, then in the row the xth element
        return data[y * width + x];
    }

    ...

But I have to wonder what the point is. I can't see any obvious efficiency difference. Both automatically deallocate memory.
Functionally, you've already got the extra step of having to zero the data (of course, you may not want this). Additionally, one thing you don't have is the total size of the data. vector stores its own size, but the array doesn't so you'd probably have to separately store height as well as width.
Plus vectors are just generally easier to program.
Comment: I only got it wrong to demonstrate how much safer the `vector` solution is ;)


Como fazer uma borda inferior a 1px?

Question: Tem como fazer uma borda com CSS inferior a 1px? Pois no meu layout ficou muito grosso.
Answer: Antes de mais nada, importante considerar estas duas situações:

Numa configuração normal em monitor convencional (HD ou menor), 1px é um "quadradinho" na tela, não tem como pintar metade dele. Seria como você perguntar "como acendo só metade da lâmpada do meu abajur?"
Num monitor HI-DPI a coisa já fica um pouco diferente. Os navegadores agrupam vários pixels formando um "pixel lógico" maior, então existe o "meio pixel". Só que como quase a especificação CSS para estes casos é inconsistente, não há um meio seguro de usar este "meio pixel" diretamente com CSS. Seria necessário usar imagens para produzir esta borda, o que mudaria essencialmente a estrutura do código (e só teria efeito em monitores de alta densidade).

O que dá pra fazer de maneira bem mais simples, é simular espessura menor usando uma aproximação, com transparência ou cálculo de cor intermediária:

A imagem da esquerda tem um pixel branco como espaço. Como era espaço demais, na da direita foi "simulado" um espaço menor usando um cinza em vez do branco original, dando ilusão de espaço menos.
Aplicando este mesmo conceito no border com CSS:

div {margin:10px;width:150px;float:left}
br {clear:both}
#pxA2 {border-bottom:2px solid rgb(255,200,0);}
#pxA1 {border-bottom:1px solid rgb(255,200,0);}
#pxAM {border-bottom:1px solid rgba(255,200,0,.5);}
#pxB2 {border-bottom:2px solid #FC0;}
#pxB1 {border-bottom:1px solid #FC0;}
#pxBM {border-bottom:1px solid #FE9;}

Com transparência:

2

1

+-.5 (simulado)

Com cores:

2

1

+-.5 (simulado)

Como você pode perceber, está longe do ideal, mas pode minimizar um pouco o problema da "grossura" da linha.
A idéia é que a linha mais "fina" tenha uma cor correspondente a uma porcentagem da cor original, e uma porcentagem da cor de fundo.
No exemplo 1, a cor é a mesma 255, 0, 0, mas no "meio pixel" usamos .5 no alpha (transparência):
#pxA1 {border-bottom:1px solid rgb(255,200,0);}
#pxAM {border-bottom:1px solid rgba(255,200,0,.5);}

No exemplo 2, fizemos a tal "transparência" manualmente, a cor original é FC0, o fundo é FFF, então o 1º F se manteve, o 2º ficou entre o C e o F (usamos E), e o terceiro entre 0 e F, então usamos 9 (não usei cálculos exatos, só aproximei para facilitar).
#pxB1 {border-bottom:1px solid #FC0;}
#pxBM {border-bottom:1px solid #FE9;}

(créditos do Pikachu ao @GuilhermeNascimento, que "pixelizou" o original)
Comment: +1 pela arte, +50 em breve pela resposta :)
Answer: Não. Não tem como fazer algo com menos de 1px, a princípio um pixel é a menor unidade de medida pra renderizar algo na tela.
Você pode tentar fazer alguns truques usando transparência, uma cor menos intensa vai dar essa impressão de ser "mais fina".

div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160, 160, 255); }

Borda 1

Borda 2

Borda 3

Borda 4

Você pode criar uma cor para este truque, neste site. Veja um exemplo com a borda vermelha.

div { border-color: #FF0000; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: #FF8B8B; }

Borda 1

Borda 2

Borda 3

Borda 4

Baseado numa resposta do SOen
Comment: Apesar de achar as demais respostas excelentes, eu concordo mais com a sua, pois a sensação de borda grossa é provavelmente devido a cor de maior contraste, ou seja não é a borda que esta grossa e sim o contraste que pode estar excessivo +1.
Comment: Se desse eu daria +3... Ótima reposta.
Comment: Dá um voto na original também :p Aí já são +2
Answer: Quando eu estou com problemas no pixels do border, ao invés de definir 1px solid black, eu uso thin solid black.
Veja (Dê um zoom no navegador pra notar a diferença):

.px-border{
    border:1px solid black;
    height: 50px;
    width: 50px;
}

.thin-border {
   border:thin solid black;
   height: 50px;
   width: 50px;
}

Veja o resultado com 500% de zoom no navegador Google Chrome:

Quando você define valor thin ("fino" em português), você está definido que o tamanho da borda será o mínimo possível.
Esse valor pode ser definido em separado na propriedade border-width, border-left-width, border-right-with, border-top-width e border-bottom-width.
Note que uma diferença entre thin e a propriedade definida em pixels é que, visivelmente, a definição em píxels acompanha o zoom do navegor, já o thin, não.
Comment: Excelente dica o `thin` ajuda bastante, é possivel notar alguma vantagem com telas de retina ou smarthphones, apesar de caso a caso. +1
Comment: Com certeza a melhor resposta. Obrigado amigo

Como fazer uma borda inferior a 1px?


How to get back to root link in jsp

Question: Could you help me, please, with one problem.
I have a project JSP + Spring MVC. It shows table with some data.
So i show some data on clients.jsp page, all my buttons have links like this: clients/add, clients/edit, etc. so they call servlets with these url's.
And i also added sort option with button clients/sort
When i push this button, my url becomes http://localhost:8080/Project/clients/sort and i see sorted data, but if i push any other buttons(add, edit) i will get a error, because Dispatcher is trying to find servlet with url clients/sort/add, not clients/add.
So i dont know how to manage with this problem, how to write links for buttons, that won't depend on page url?
Some code from my project:
Buttons:

                <a class="sort_firstName"
                   href="<c:url value="/clients/sort/firstnameup"/>">
                    <spring:message code="label.up"/>

            <a class="add_order"
               href="<c:url value="/clients/addOrder/${client.id}"/>">
                <spring:message code="label.addOrder"/>
             /

            <a href="<c:url value="/clients/edit/${client.id}"/>">
                <spring:message code="label.modify"/>

Controller:
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String newClient(Model model) {
    Clients client = new Clients();
    client.setId(0);
    model.addAttribute("clientAdd", client);
    return "clientForm";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addClient(@ModelAttribute("clientAdd") Clients client,
                        BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "clientForm";
    }
    clientsService.createClient(new CreateClientEvent(client));
    return "redirect:/clients";
}

upd:
<form id="dialog-form" class="form-horizontal" action="clients/add" method="post">

        ....

            <button class="btn btn-primary" type="submit" id="addClient" ><c:out value="Create"/></button>

</form>

Comment: Please put the jsp code of the add button, not addOrder button... You're probably not using c:url on the add button.
Comment: i added add button, it is in form with action="clients/add"
Answer: You should use c:url otherwise your link will be relative to current url.
<c:url value="/clients/add" var="addUrl"/>
<form id="dialog-form" class="form-horizontal" action="${addUrl}" method="post">

Answer: First of all your name for the controller should be different. It should have only one controller named /add . IN the href you dont need C: taglib. you can use it in the following manner- href="add/${client.id}" and you need to catch the client ID in the controller with @RequestParam("Id") long Id. You controller cannot be matched because you have same name in two controllers and you have to only specify the controller name and not the full path like you have done.
Comment: -1 because you CAN have 2 requestMapping with same value but different method. And also using `href="add/${client.id}` is exactly why the poster has pb. If he is on the `clients/sort` page then using your href will send user to `clients/sort/add` instead of `clients/add`

How to get back to root link in jsp


Arquivo html não identifica CSS

Question: Fui por um estilo na página e o HTML não usa o arquivo CSS.
Primeiro coloquei assim:
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="bootstrap.css">

E no console dava esta mensagem:

Resource interpreted as Stylesheet but transferred with MIME type
text/html: "http://localhost:4000/main.css".

Então coloquei: <link rel="stylesheet" type="text/css" href="main.css"> e continuava dando a mesma mensagem.
Troquei para <link rel="stylesheet" type="text/html" href="bootstrap.css"> e a mensagem parou de dart no console, mas meus stylos não funcionam, é como se eu não tivesse chamando nada, e os arquivos estão na mesma pasta da index.
O que pode ser?
************ Atualizações ***********
Conforme pediram, segue código do servidor:
var http = require('http').createServer(server);
var fs = require('fs');

function server(req, response){
    response.writeHead(200);
    response.end(fs.readFileSync('view/index.html'));
};

http.listen(4000, function(){
  console.log("x------------------x");
  console.log("x Servidor On-line x");
  console.log("x------------------x");
});`

Comment: O que você está usando para servir os arquivos? O problema está na configuração do servidor que "diz" que o arquivo de estilo é CSS e não HTML.
Comment: Então, eu fiz um servidor rapido com node:

var http = require('http').createServer(server);
var fs = require('fs');

function server(req, response){
    response.writeHead(200);
    response.end(fs.readFileSync('view/index.html'));
};

http.listen(4000, function(){
  console.log("x------------------x");
  console.log("x Servidor On-line x");
  console.log("x------------------x");
});`

E é só isso...
Comment: @RafaelaCordeiro, não é a melhor opção fazer um servidor "rápido" com o módulo `http`. Você pode optar pelo `express` ou `http-server`. Dito isto, segue um "pequeno" código para  solucionar seu problema. https://stackoverflow.com/a/29046869/9101590
Comment: Pode postar seu arquivo css por favor se não for muito grande.
Comment: O problema então está claramente no servidor que você criou. Use um servidor pronto para desenvolvimento - ou poste o código do seu servidor para que possa ser corrigido: é ali que está seu problema específico.

(você pode usar a linguagem python instalada no seu sistema para servir arquivos estáticos diretamente: `python3 -m http.server 4000` )
Answer: Seu MIME type está errado, não é type="text/html" é type="text/css"
Assim ele não carrega:
<link rel="stylesheet" type="text/html" href="bootstrap.css">

O correto é assim:
<link rel="stylesheet" type="text/css" href="bootstrap.css">

Uma dica é usar o DevTools do Chrome por exemplo para verificar se o arquivo .CSS carregou corretamente. No Chrome abra seu documento, aperte F12, vai na Aba Network, masque o CSS e depois de de um F5
Comment: @hugocsl, foi a primeira coisa que notei ao olhar as *respostas* daqui. Infelizmente ainda existem pessoas que querem tirar algum aproveito, mas não sabem que citar a fonte é tão útil quanto expandir o conhecimento.
Comment: Além de alertá-lo você orientou sobre o fato. Acredito que ele já esteja ciente disso. Espero muito que seja leiguice!
Comment: Então, eu já fiz isso. Lá eu expliquei: "coloquei:  e continuava dando a mesma mensagem. Troquei para  e a mensagem parou de dar no console, mas meus estilos não funcionam.
Comment: Iniciei um servidor node e pensei nisso estar dando algum conflito, peguei os arquivos (index e os css's) copiei para uma pasta vazia, abri no navegador e funcionou. Tem algo de errado por conta do servidor?

`var http = require('http').createServer(server);
var fs = require('fs');

function server(req, response){
    response.writeHead(200);
    response.end(fs.readFileSync('view/index.html'));
};

http.listen(4000, function(){
  console.log("x------------------x");
  console.log("x Servidor On-line x");
  console.log("x------------------x");
});`
Comment: Talves seu server não reconhece esse MIME type...  Conferiu se o CSS está aparecendo na Aba Network? De Node eu não entendo nada...
Comment: Realmente, foi descuido, estava sem type,já adicionei e está aparecendo no network corretamente, mas não funciona o estilo mesmo assim.
Comment: Vi que esse problema tem muita tendência de ser problema relacionado ao servidor. Encontrei um caso semelhante no [SO](https://stackoverflow.com/questions/22631158/resource-interpreted-as-stylesheet-but-transferred-with-mime-type-text-html-see), dá uma olhada...
Comment: @AndréFilipe legal a referência parece que lá tem até uns truques pra tentar resolver usando `/` no path, ou `#`. Mas ai vou deixar pro autor da pergunta analisar... *O interessante foi ver que a outra resposta que derem aqui é **basicamente um plágio**, o cara traduziu o texto inteiro na cara dura e nem citou a fonte...*
Comment: @AndréFilipe e para piorar eu dei a dica pro cara, ele viu, comentou que era falta de atenção da parte dele e ainda assim não colocou a fonte.... Vai entender... :/
Answer: Opa então para você poder carregar um arquivo css de um diretório no Node.js você precisar primeiro determinar a pasta estática onde ficam esses arquivos, o que você pode fazer é o seguinte:

Criar uma pasta na raiz do projeto chamada public
Dentro dessa pasta public você coloca a pasta com os seus arquivos css

Dai no seu app.js você vai colocar o seguinte comando se você estiver utilizando o express
app.use('/public', express.static('public'));

E dentro do seu arquivo index html ao invés de ficar:
<link href="css/style.css" rel="stylesheet" type="text/css"/>

Vai ficar:
<link href="/public/css/style.css" rel="stylesheet" type="text/css" />

Espero que ajude
Comment: E solucionei o caso, mas não usei o express, usei o angular http-server, e dai funcionou. Eu precisava mesmo adicionar um servidor. Eu ainda estou aprendendo Angular, então estou em busca de ver o melhor caminho ainda. Obrigada :)
Answer: Vamos começar com a explicação:
Os navegadores fazem solicitações HTTP para servidores. O servidor então faz uma resposta HTTP.
Ambas as solicitações e respostas consistem em vários cabeçalhos e um corpo (às vezes opcional) com algum conteúdo.
Se houver um corpo, então um dos cabeçalhos é o Content-Type que descreve o que é o corpo (é um documento HTML? Uma imagem? O conteúdo de uma submissão de formulário? Etc.).
Quando você solicita sua folha de estilo, seu servidor está dizendo ao navegador que é um documento HTML (Content-Type: text/html) em vez de uma folha de estilo (Content-Type: text/css).
Mude de Content-Type: text/html:
<link rel="stylesheet" type="text/html" href="bootstrap.css">

para:
<link rel="stylesheet" type="text/css" href="bootstrap.css">

Comment: Amigo quando vc copiar a resposta do StackOverflow em inglês é interessante vc pelo menos citar a fonte. Pegar alguma resposta de lá não é problema, o que vc pode considerar ser ético ou não é citar a fonte de onde vc pegou a resposta! Não é um ataque pessoal ok, é só uma dica beleza. []´s
Comment: Então, eu já fiz isso. Lá eu expliquei:
"coloquei:  e continuava dando a mesma mensagem.
Troquei para  e a mensagem parou de dar no console, mas meus estilos não funcionam.
Comment: Iniciei um servidor node e pensei nisso estar dando algum conflito, peguei os arquivos (index e os css's) copiei para uma pasta vazia, abri no navegador e funcionou. Tem algo de errado por conta do servidor?

`var http = require('http').createServer(server);
var fs = require('fs');

function server(req, response){
    response.writeHead(200);
    response.end(fs.readFileSync('view/index.html'));
};

http.listen(4000, function(){
  console.log("x------------------x");
  console.log("x Servidor On-line x");
  console.log("x------------------x");
});`
Comment: Beleza! Foi a falta de atenção. Obrigado

Arquivo html não identifica CSS


Como fazer o ENTER pular de campo ao invés de enviar?

Question: Comando para gravar informações no banco:
<button id="btnslv" type="submit" class="btn btn-success btn-block" name="btnslv" value="0">SALVAR</button>

Meu Form:
<form class="" id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" name="cadastro" method="post" enctype="multipart/form-data">

Já tentei trocar o "submit" por "button" e até deu certo, mas ele não grava as inforamções ao banco.
Também já tentei usar "onClick = "document.cadastro.submit()"", mas também não deu certo.
Vocês tem alguma ideia de como eu possa proceder?
Answer: Olá, tudo bem? Encontrei uma resposta que pode lhe ajudar!
Caso queira ver a resposta original Clique aqui

   $("input, select", "form") // busca input e select no form
    .keypress(function(e){ // evento ao presionar uma tecla válida keypress

       var k = e.which || e.keyCode; // pega o código do evento

       if(k == 13){ // se for ENTER
          e.preventDefault(); // cancela o submit
          $(this)
          .closest('tr') // seleciona a linha atual
          .next() // seleciona a próxima linha
          .find('input, select') // busca input ou select
          .first() // seleciona o primeiro que encontrar
          .focus(); // foca no elemento
       }

    });

<form id="documento" name="documento" method="post" action="inclusao.php" onsubmit="return validaCampo(); return false;">

Cadastro de Documento

        CPF/CNPJ:
        <input name="CNPJ" type="text" id="CNPJ" size="20" maxlength="14" />
          * somente números

        Data Recebimento:

          <input type="text" name="DataRec" id="DataRec" size="10" maxlength="10" /> *

        Tipo de Documento:

          <select name="TipDoc" id="TipDoc">
            <option value="NF">NF</option>
            <option value="CTO">CTO</option>
            <option value="MTO">MTO</option>
            <option value="OUTROS">OUTROS</option>
          </select> *

        Número do Documento.:
        <input type="tel" name="NumNFC" id="NumNFC" size="9" maxlength="9" /> *

        Quantidade (Volume)
        <input name="QTDVol" type="tel" id="QTDVol" size="4" maxlength="4" /> * em litros

        Processo
        <input name="proces" type="text" id="proces" size="14" maxlength="14" /> *

        Local de Entrega:
        <input name="CDRDES" type="text" id="CDRDES" maxlength="15" size="15" />
          *

        Fornecedor:
         <input name="FORNEC" type="text" id="FORNEC" maxlength="20" size="20" /> *

            <input name="cadastrar" type="submit" id="cadastrar" value="Confirmar" />

            <input name="limpar" type="reset" id="limpar" value="Limpar Campos preenchidos!" />

            * Campos com * são obrigatórios!

  </form>


Filter MongoDB query to find documents only if a field in a list of objects is not empty

Question: I have a MongoDB document structure like following:
Structure
{
    "stores": [
        {
            "items": [
                {
                    "feedback": [],
                    "item_category": "101",
                    "item_id": "10"
                },
                {
                    "feedback": [],
                    "item_category": "101",
                    "item_id": "11"
                }
            ]
        },
        {
            "items": [
                {
                    "feedback": [],
                    "item_category": "101",
                    "item_id": "10"
                },
                {
                    "feedback": ["A feedback"],
                    "item_category": "101",
                    "item_id": "11"
                },
                {
                    "feedback": [],
                    "item_category": "101",
                    "item_id": "12"
                },
                {
                    "feedback": [],
                    "item_category": "102",
                    "item_id": "13"
                },
                {
                    "feedback": [],
                    "item_category": "102",
                    "item_id": "14"
                }
            ],
            "store_id": 500
        }
    ]
}

This is a single document in a collection. Some field are deleted to produce minimal representation of the data.
What I want is to get items only if the feedback field in the items array is not empty. The expected result is:
Expected result
{
    "stores": [
        {
            "items": [
                {
                    "feedback": ["A feedback"],
                    "item_category": "101",
                    "item_id": "11"
                }
            ],
            "store_id": 500
        }
    ]
}

This is what I tried based on examples in this, which I think pretty same situation, but it didn't work. What's wrong with my query, isn't it the same situation in zipcode search example in the link? It returns everything like in the first JSON code, Structure:
What I tried
query = {
    'date': {'$gte': since, '$lte': until},
    'stores.items': {"$elemMatch": {"feedback": {"$ne": []}}}
}

Thanks.
Comment: I tried it but still having issues actually. I will inform you more. Thanks for the answer.
Comment: Do you've store_id in first object of stores array as well ? Please mention your mongoDB version..
Comment: Did it work or still having issues ?
Answer: Please try this :
db.yourCollectionName.aggregate([
{ $match: { 'date': { '$gte': since, '$lte': until }, 'stores.items': { "$elemMatch": { "feedback": { "$ne": [] } } } } },
{ $unwind: '$stores' },
{ $match: { 'stores.items': { "$elemMatch": { "feedback": { "$ne": [] } } } } },
{ $unwind: '$stores.items' },
{ $match: { 'stores.items.feedback': { "$ne": [] } } },
{ $group: { _id: { _id: '$_id', store_id: '$stores.store_id' }, items: { $push: '$stores.items' } } },
{ $project: { _id: '$_id._id', store_id: '$_id.store_id', items: 1 } },
{ $group: { _id: '$_id', stores: { $push: '$$ROOT' } } },
{ $project: { 'stores._id': 0 } }
])

We've all these stages as you need to operate on an array of arrays, this query is written assuming you're dealing with a large set of data, Since you're filtering on dates just in case if your documents size is way less after first $match then you can avoid following $match stage which is in between two $unwind's.
Ref 's :
$match,
$unwind,
$project,
$group
Answer: This aggregate query gets the needed result (using the provided sample document and run from the mongo shell):
db.stores.aggregate( [
  { $unwind: "$stores" },
  { $unwind: "$stores.items" },
  { $addFields: { feedbackExists: { $gt: [ { $size: "$stores.items.feedback" }, 0 ] } } },
  { $match: { feedbackExists: true } },
  { $project: { _id: 0, feedbackExists: 0 } }
] )


Basic solution and linearly independent columns - exercise 2.3 Bertsimas and Tsitsiklis

Question: I am trying to solve exercise 2.3 of the book "Introduction to linear optimization" by Bertsimas and Tsitsiklis, which states:
$\textbf{
Exercise 2.3 (Basic feasible solutions in standard form polyhedra with
upper bounds)}$ Consider a polyhedron defined by the constraints $Ax = b$ and
$0 \leq x \leq u$, $u\geq0$ and assume that the matrix has linearly independent rows.
Prove an analog of Theorem 2.4.
Where Theorem 2.4 is:
$\textbf{Theorem 2.4}$ Consider the constraints $Ax=b$ and $\geq 0$ and as
sume that the $m \times n$ matrix $A$ has linearly independent rows. A vector
$x \in \mathbb{R}^n$ is a basic solution if and only if we have $Ax = b$, and there
exist indices $B (1) , . . . , B (m)$ such that:
$\bullet\ \text{The columns $A_{B(1)},...,A_{B(m)}$ are linearly independent} \\ \bullet\ \text{If $i \neq B(1),...,B(m)$ then $x_i=0$}$

My reformulation of theorem 2.4 would be the following:
$\textbf{Theorem}$
Consider the constraints $Ax = b$ and $0\leq x\leq d$ and assume that the $p \times n$ matrix $A$ has linearly independent rows. A vector $x \in \mathbb{R}^n$ is a basic solution if and only if we have Ax = b, and there exist indices $B (1) , . . . , B (p)$ such that:
$\bullet\ \text{The columns $A_{B(1)},...,A_{B(p)}$ are linearly independent;}\\
\bullet\ \text{If $i\neq B (1) , . . . , B (p)$, then $x_i = 0 $ or its respective upper bound $d_i$.}$
$\textit{Proof}$:
Suppose that $x$ satisfies both conditions.
Then it is true that:
\begin{align}
\begin{split}
Ax  = \sum_{i=1}^{p} A_{B(i)} x_{B(i)}+\sum_{i\neq B(1),...B(p)} A_i x_i = b\\
\sum_{i=1}^{p} A_{B(i)} x_{B(i)} =b-\sum_{i\neq B(1),...B(p)} A_i x_i
\end{split}
\end{align}
Since the columns $A_{B(i)}$ $i=1,...,p$ are linearly independent, $x_{B(i)}$ $i=1,...,p$ are uniquely determined.
By Theorem 2.2 , there are n
linearly independent active constraints, and this implies that x is a basic
solution.
For the converse, let us assume x is a basic solution.
Let $B(1),...,B(k)$ all the indices such that $x_{B(i)} \neq 0$ and $x_{B(i)} \neq d_i$ for all $i=1,...,k$.
Since $x^*$ is a basic solution, the system of equations formed by the active constraints
$\sum_{i=1}^{n} A_i x_i = b$, $x_i=0$, $x_
i=d_i$ $i \neq B(1),...B(k)$ has a unique solution (Theorem 2.2).
This implies that the columns $A_{B(1)},...,A_{B(k)}$ are linearly independent and so $k\leq p$.
Since $rank(A) = p$, we can choose $p-k$ more columns so that the columns $A_{B(1)},...,A_{B(p)}$ are linearly independent. Moreover if $i \neq B(1),...,B(p)$, then it is also true that
$i \neq B(1),...,B(k)$, since $k \leq p$ and $x_i=0$ or $x_i=d_i$.

Where
$\textbf{Theorem 2.2}$
Let $x^*$ be an element of $\mathbb{R}^n$ and let
I={i : $a_i^{'}x_i=b_i$} be the set of indices of constraints that are active at $x^*$.
Then, the following are equivalent:
$\bullet\ \text{There exist n vectors in the set ${a_i : i \in I}$ that are linearly independent;}\\
\bullet\ \text{The system of equations $a^{'}_ix=b_i$ has a unique solution}$
Is my reformulation (and proof) of theorem 2.4 correct?
Comment: related material [here](https://math.solverer.com/library/dimitris_bertsimas/introduction_to_linear_optimization/exercise_2-3?utm_source=stackexchange.com&utm_medium=link).
Answer: Yes, I think yours is right.
My answer:
Procedure:
In order to find out the proper basic solution, there must be n linearly independent constraints that are active. Therefore, first we must ensure that all the constraints in Ax=b are active, and that's not enough. We still need another n-m constraints in order to get n linearly independent active constraints.
However, differing from the case of standard form, now we can see there are more choices for us to take when selecting the value of nonbasic variables. For active choice, we can either choose 0 or m for them to be.
Finally, we come up with the following procedure:

Choose m linearly independent columns $A_{B(1)},...,A_{B(m)}$·
Let ${X_i}$ become either 0 or m for all i not in $I=\{B(1),...,B(m)\}$.
Solve the system of m equations $Ax= b$ for the unknowns $X_{B(1)},...,X_{B(m)}$.

Then we are going to prove a new theorem analogous to Theorem 2.4.
Theorem:Consider the constraints $Ax = b$ and $0 \leqslant x \leqslant u$ and assume that the $m$x$n$ matrix $A$ has linearly independent rows. A vector $x \in R^n$ is a basic solution if and only if we have $Ax = b$, and there exist indices $B(1),...,B(m)$ such that:

The columns $A_{B(1)},...,A_{B(m)}$ are linearly independent;
If $i\neq B(1),...,B(m)$, then $X_i = 0$ or $X_i = m$.

Proof:
Consider some $x \in R^n$ and suppose that there are indices $A_{B(1)},...,A_{B(m)}$ that satisfy (1) and (2) in the statement of the theorem.The active constraints $X_i = 0$ or $X_i = m$ forall i not in $I=\{B(1),...,B(m)\}$, and $Ax = b$ imply that
$$
\sum_{i=1}^{m} \mathbf{A}_{B(i)} x_{B(i)}=\sum_{i=1}^{n} \mathbf{A}_{i} x_{i} - km=\mathbf{A} \mathbf{x} - km=\mathbf{b}- km = constant
$$
Since the columns $A_{B(1)},...,A_{B(m)}$  are linearly independent,$X_{B(1)},...,X_{B(m)}$ are uniquely determined. Thus, the system of equations formed by the active constraints has a unique solution. By Theorem 2.2, there are n linearly independent active constraints, and this implies that x is a basic solution.
For the converse, we assume that x is a basic solution and we will show that conditions 1 and 2 in the statement of the theorem are satisfied.
Since x is a basic solution, the system of equations formed by the active constraints have a unique solution. Equivalently, the equation $\sum_{i=1}^{m}\mathbf{A}_{B(i)} x_{B(i)}=\mathbf{b}- km$ has a unique solution. It follows that the columns $A_{B(1)},...,A_{B(m)}$  are linearly independent, fitting the statement 1 and 2.


Why Are These Two Morphisms the Same?

Question: I am reading Max Karoubi's "K-Theory" and I think I'm overlooking some trivial fact.  We have a vector bundle $E\rightarrow X$ and a morphism $p:E\rightarrow E$ with $p^2=p$.  He is showing that $\ker p$ is locally trivial.  First he assumes that $E=X\times V$ for a vector space $V$.  Here's where I'm stuck:
He defines $f:X\longrightarrow \operatorname{End}(V)$ by
$$
f(x)=1-p_{x_0}-p_x+2p_xp_{x_0},
$$
where $p_x$ is the restriction of $p$ to the fiber over $x$ and $x_0$ is a basepoint.  The claim is that $p_{x_0}\circ f(x)=f(x)\circ p_x$.  When I compute both sides I get
$$
2p_{x_0}p_xp_{x_0}-p_{x_0}p_x=2p_{x}p_{x_0}p_{x}-p_{x_0}p_x
$$
which says
$$
2p_{x_0}p_xp_{x_0}=2p_{x}p_{x_0}p_{x}.
$$
Why is that true?  Thanks.
Comment: Maybe I'm being really dumb, but doesn't $p_x: V\to V$? What exactly is meant by equality of maps in this sense? It seems $p_{x_0}\circ f: X\to End(V)$, but $f\circ p_x: V\to $ something, I'm not sure. Sorry if I appear to have no idea what I'm talking about.
Comment: @Matt:  You are not being foolish.  It should read $$p_{x_0}\circ f(x)=f(x)\circ p_x.$$  It has been corrected.  Thanks.
Comment: For those who want to take a look at it: Page 27 [here.](http://books.google.com/books?id=fJzlLkHBYTYC&printsec=frontcover&dq=Max+Karoubi+%22K-Theory%22&source=bl&ots=s8I85R68xD&sig=NrkH5wPQqAnzcvk8awbwyDvQJMc&hl=de&ei=hldUTZHkHMPpOfOZ-KIF&sa=X&oi=book_result&ct=result&resnum=2&ved=0CCUQ6AEwAQ#v=snippet&q=px%20p0%20%22is%20the%20trivial%20bundle%22%20%22Since%20the%20question%22&f=false)
Answer: That's probably a typo. Try $p_x f(x)= f(x) p_{x_0}$ or, alternatively, $f(x)=1-p_{x_0}-p_x +2 p_{x_0} p_{x}$ in the rest of the proof (which I can't see).
As given, the equality is not true. Think of 2 lines, say of slope 2 and 1/2, in R^2 and the projections along vectors (0,1) and (1,0). Then the image of the first composition is all of the first line,  and of the second one all of the second line. No way such maps can be equal.
Comment: Your alternate solution does the job.  I just have to re-work his proof a bit.  Thanks.

Why Are These Two Morphisms the Same?


SSL stopped working on IIS6 after Windows Update

Question: I have a Windows 2003 image with IIS6 installed that just installed a block of Windows Updates.  This webserver was using port 443 and an SSL certificate properly up until this patch, and it will no longer respond at all on port 443 to requests.
I have tried removing and re-installing the certificate, and it will still not respond on port 443.
Is the metabase corrupted?  Is this something I can easily rebuild?
-- UPDATE --
After some further investigation, this server image that is installed on the Amazon EC2, somehow invalidated its SSL certificates when I performed a 'bundle' operation on the AMI.  Is there any way to avoid having to re-key an SSL cert when you launch a bundled AMI?
Comment: Do you know which updates were installed? Did you stage them in a test environment first?
Answer: I think if you disable the Ec2Config service you can avoid this problem. My understanding is that after a bundle this service generates a new key for the server.
Note that this may have other implications.


IIS7 - How do I update the alias after site creation?

Question: I have a web application directory (subsite of the main - default website).  I want to update the Alias that I originally chose.  How do I do it in IIS7?

In the file mentioned by Coding Gorilla I see
<application path="/SiteAlias" applicationPool="DefaultAppPool">

and
 <location path="Default Web Site/SiteAlias">

do I need to update both of these?
Comment: Can you define "Alias"?
Comment: `http://site/alias`  Essentially its what I would call the alias to access the virtual directory.  Though, I'm not sure if virtual directories exist anymore in IIS7.
Comment: Ok, so you just want to change the directory name. Are you wanting to do this with the IIS console or do you not have that access?  (And yes, they still exist)
Comment: I typically use start > run > inetmgr
Answer: You can't actually do this thru the IIS Manager console, but what you can do is edit the C:\Windows\system32\inetsrv\config\applicationHost.config' file.  Find the relatednode and update thepath` attribute.
Comment: Ah,that's pretty disappointing that it can't be done through the GUI.
Comment: Yea, I thought you could as well, but I tried and wasn't able.
Comment: I had to open it with regular Notepad as Notepad++ was unable to save the edits using 64 bit OS: [unable-to-save-applicationhost-config-file](http://stackoverflow.com/questions/11280076/unable-to-save-applicationhost-config-file)


Is a leap of a 4th in the Alto voice too large when voice leading?

Question: I am trying to voice lead IV6 V6 I in A major with an ascending bassline and this is the best I could come up with but there is a leap of a 4th. Is this too much? Could someone please tell me what Im doing wrong?
Comment: You have parallel octaves between soprano and tenor.  Fix those, and you may find that you no longer have a need for the leap of a fourth in the alto.
Comment: thanks but I would still like to know if a 4th is allowed?
Comment: Any other way I tried it then I have parallel 5ths :( and I cant double the G # in the V6 chord either since it is the leading tone
Answer: The leap of a fourth is fine in any voice.  In the sort of pseudo-19th-century-hymnody style of four-part writing that many music theory textbooks use, leaps bigger than a fourth or fifth are relatively rare in upper voices (but can sometimes occur).
(I call it 19th-century hymnody style, because it's not really "chorale style," despite what textbooks say.  Actual Bach chorales frequently have giant leaps all over the place.)
To fix your voice-leading problem here, the quickest solution is to have the tenor move up to E, i.e., D-E-C♯.  That's also a better doubling for the V chord anyway.
Comment: Also commonly taught that a leap should be followed by a return by step in the opposite direction.
Answer: When roots move by single step it's a special voice leading situation, because there are no common tones to hold between triads, so I first looked at the root position standard movement. The basic voice leading is to have all the upper voices move opposite the bass to the closest next tones.

...note colors are orange=tenor, green=alto, blue=bass.
But what happens when F# to G# is taken from that voice leading and placed in the bass?

Notice the desired ascending bass of F# G# A then splits the F# G# part of the line between the tenor and alto voices. If we remove the root position D E bass and then drop tenor F# and alto G# down into the bass we account for the leap of A down to E. It's the remnants of the initial parts A in alto and E in tenor.
If we consider the descending A to E as an alto leap and then fill a tenor for four parts with doubled roots we get...

...the second harmonization just holds the tenor D to get a dominant seventh V.
But that's not necessarily the best way to harmonize bass F# G# A. It's just a way to show how we end up with leaping voices.
The desired ascending bass F# G# A isn't root position harmony, so we don't have to move all the upper voices opposite the bass. Fenaroli's rule of the octave give these positions for ascending bass ^6 ^7 ^1...

...that shows the bass/soprano movement from IV6 to V6/5 in parallel thirds/sixths or oblique holding the subdominant to get a seventh for V6/5.
Comment: I would note that the Fenaroli examples aren't really about "voices" in the literal vocal sense, or in the "hymn-texture" abstract music theory sense.  Fenaroli was writing a keyboard harmonization for a given bass line.  As Michael says in the comment, you can spread out the notes as needed, but as we can see in the examples, "voices" tend to appear or disappear on a whim in many keyboard realizations (often to avoid parallels or other voice-leading problems).
Comment: Thanks Michael. So in your opinion which do you think is the best way to Harmonize the ^6 ^7 ^8 bassline? Changing the V to a 65 chord certainly seems to smooth it out a bit.
Comment: I don't think of this in terms of "best" harmonization. Other than the first example, root position, upper voices in closed position, as just a _model_ of voice leading principles, you have _choices_. Fenaroli gave three examples just to cover the various endings of the soprano. But, you can reduce those to simply say `IV6 V6 I` gets harmonized as ascending `6/3` chords as a "prototype" then the seventh is added for `V65`. You can rearrange the voices into different octave for open positions, or make typical omissions for 3 or 2 part harmony.
Comment: Yes, not true voices/parts. My original source for Fenaroli is the author Gjerdingen and he did explain the rule wasn't a voice leading model. In fact, from the Fenaroli original (facsimiles) I've seen, the rules were only a _figured bass_ line, no actual upper voices written out.
Answer: A leap of a 4th is fine.  But try to make each part a coherent melodic line.  It can be difficult to make the alto an INTERESTING melodic line in hymn-style harmony, but at least try to avoid random jumps.
If you want a 'rule', try not to follow a big leap with another one in the same direction.


Install certificate in .cer format on Windows Server 2008 - IIS 7

Question: My task is to install a certificate which I got in .p7b format from my company. IIS 7 can import a certificate in .cer format by using the "Complete Certificate Request..." option. Using the Certificates MMC snap-in I managed to convert the .p7b file to .cer by importing, then exporting it.
Unfortunately when I try to use it with the "Complete certificate request..." option, IIS 7 complains that it can't find the certificate request, so it can't proceed.
What options do I have in this situation? Do I need a .pfx file which has the private key in it, or I can install the certificate in .cer format? I want to use it in an https binding with one of the websites on the server.
Answer: It sounds to me like the certificate request (and therefore the private key)was not generated on your webserver is that correct?
If it is correct then you will need a certificate with a private key  in order to install it. This is the certificate in pfx format as you correctly identify.
The .p7b file will not have a private key.
Alternatively you can generate the certificate request yourself using the following mechanism:
CREATE INF file as follows
[Version]
Signature="$Windows NT$
[NewRequest]
Subject="etc"
KeySpec=1
Exportable=1
MachineKeySet=TRUE
ProviderName="CSPName"
ProviderType=1
[RequestAttributes]
CertificateTemplate=
Then use the following commands at the command prompt
certreq -new infile.inf reqfile.req //where infile.inf is the file above and reqfile is the output request file
Send this output request to the guys who issue your certificates and you will get the correct p7b back that will install.
Regards
Mark Sutton
http://www.blacktipconsulting.com


How to make each header in a table clickable and add a chart to it?

Question: I have used the Views module to display an external database (which is working fine), but I want to make each header clickable and add a chart.
Is there a module to do this, or is there a way I can do this?
I found a few charting modules; some are good but they require me to create each chart manually, using the style and the data gets feed to it dynamically. The problem is that my tables have many headers; I flip the rows and columns but there are over 100 headers in it.
Answer: There's no drag-and-drop solution. You would either have to create a custom module yourself that would do what you want, modify a module that gets close to what you want or use one of the solutions out there that makes you enter things in manually.


Sketch the set of points represented by the following quadratic equation.

Question: Sketch the set of points represented by the quadratic equation: $$\begin{pmatrix} x & y\end{pmatrix} \begin{pmatrix} 1 & -2 \\ -2 & 4\end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix} = 1$$
I multiplied this out and got: $$x-2y=\pm 1$$
Is the solution just these two lines drawn on an $xy$ plane?
Answer:
Is the solution just these two lines drawn on an $xy$ plane?

That's right, you would call this a degenerate conic.
Comment: @Derek Are you sure you get different plots? ([plot1](http://www.wolframalpha.com/input/?i=plot+%7Bx%5E2-4xy%2B4y%5E2+%3D1%7D) and [plot2](http://www.wolframalpha.com/input/?i=plot%7Bx-2y%3D1,x-2y%3D-1%7D))
Comment: Alright, problem solved! :-)
Comment: I have since noticed that if I plot $x^2-4xy+4y^2 =1$ I get a different graph than $x-2y=\pm 1$. Which one is correct or which one is being asked for in the question?
Comment: Oops , I had $y^2$ instead of $4y^2$. They are the same.


How to run activex control in Windows 8

Question: I have an intranet application that uses activex. It runs fine in Windows 7 but not in Windows 8. I've used caspol to grant full trust, I've set IE 10 to allow downloading and running of activex controls.
I've even tried to run it in Chrome with an activex addon.
Nothing seems to work.
I'd really appreciate any insight. Jon
Answer: If you're asking how to get ActiveX controls to work in IE in the modern/metro interface, you're completely out of luck; ActiveX controls do not work there.
If you want to get an ActiveX control to work, you have to switch to the standard desktop and launch IE from there. ActiveX does work there. I use it to access Remote Desktop Web App.
Comment: Thanks, both you and Steven - I am running IE from the desktop and I have it set to IE9 compatibility mode. The control is in an object tag so it doesn't show up as a downloaded program. The object is being found by IE. I wrote the dll and the web page both have been working for over a year under Win 7 - Win 8 not so good so far.
Answer: If the ActiveX control is written in .Net 3.5, you have to install that framework in Windows 8, as it is not included by default.
http://msdn.microsoft.com/en-us/library/hh506443(v=vs.110).aspx
Answer: Try first to determine if the activex (cab or dll/ocx files) is downloaded to the user's browser.
You can use Fiddler for that.
Once you know the files ar actually downloaded you can tweak the browser's security settings to make sure the activex are installed.
You can see the installed activex programs under the %windir%\Downloaded Program Files" folder.
And try to lower the IE security settings for that site while you are troubleshooting this.

How to run activex control in Windows 8


why do I keep getting the error Cannot resolve symbol Fragment activity?

Question: Why does it keep showing up red If I have the library imported?
Comment: How have you imported the appcompat library?
Comment: yes that would be import android.support.v4.app.FragmentActivity;
Comment: has the library "android.support.v4" been imported into the project? Like in the "libs" folder? You may need to restart the IDE
Comment: hey i downloaded the libraries on the extras on sdk. But the lib folder appears to be empty? any pointers?
Comment: @J.B. `import android.support.v4.app.FragmentActivity;` imports the `FragmentActivity` **class** into the current .java file. You also need to import the full appcompat library into Eclipse and reference it from your project.
Answer: You need to import the appcompat library into your project.  For details how to do this, see Support Library Setup.


Tabela dinâmica com dados vindo de uma input - js

Question: Oii gente, tudo bem?
Criei uma função que imprime os números primos, de acordo com o valor inserido pelo usuário no input.
Estou com uma dificuldade de acessar esse número para que a função funcione e retorne uma array e imrprir essa array numa tabela dinâmica. Estou iniciando ainda os estudo, alguém consegue me dar uma ajuda?
Segue o código:

            <form class="text-center p-5" action="#!">

Projeto - Números Primos

                        <input type="text" id="numerocalculo" class="form-control" name="numerocalculo" placeholder="Insira um número aqui" onblur="desafioPrimos(this);">
                        <input class="btn btn-outline-primary waves-effect btn-sm my-4 btn-block" type="button" value="Enviar" onclick="geradorTabela()">

</form>

Answer: Eu posso indicar qual o seu erro ao tentar acessar o valor do input.
Já adianto que existem outros problemas no código, e apenas essa correção não irá faze-lo funcionar, mas quanto a pergunta, eis a explicação.
No início do seu código, você está buscando o valor do input numerocalculo com a seguinte linha de código
var numero = document.getElementById('numerocalculo').value;

value é uma propriedade do tipo string, que é passado por valor, não por referência. Isso significa que se o valor do input for alterado, isso não irá refletir na sua variável numero, numero continuará representando o mesmo valor de quando ela foi inicializado, esse valor por sua vez é o que o seu input continha quando a página foi carregada: uma string vazia
Para pegar o valor numérico de numerocalculo no momento que a função desafioPrimos for executada, você deveria inicializar essa variável dentro da função:
function desafioPrimos() {
    var numero = parseInt(document.getElementById('numerocalculo').value);
    var primos = [];

    // código para popular o array primos aqui

    return primos;
}

Também é possível que o valor do input não seja um valor numérico válido, então lembre de tratar essa possibilidade.
Comment: Obrigada, consegui que retornasse a array, inseri o parseInt dentro da função como sugeriu!


Rubber banding with mouse on model not on screen position

Question: I am trying to draw a triangle or rectangle using mouse with Rubberband approach. There are approaches available for Rubber band approach on screen position but i want it on the model position. Can anyone suggest some way to achieve that?
Answer: You should always draw the rubber band in screen space. Once the selection has been performed, transform the rubber band limits into model space planes (the lines of the rubber band translate into a set of 4 planes, that define the selection volume).


Can this infinite vector still span a dual subspace?

Question: Let's say I have a vector space $V$ of infinite dimension. Then, if we look at the dual basis, it does not actually span the whole dual vector space $V^*$, since linear combinations only allow finite sums. So if i take the canonical basis $B$ of $V$, then the subspace spanned by the dual basis does for example not contain a linear form $a^* : V\rightarrow K$ with $a^*(b_i) = 1$ for all $b_i$.
My question now is: If I took the subspace, which is spanned by the dual "basis" $b^*_i$ and swapped the first vector $b_1^*$ for the linear form $a^*$ I mentioned above, does this new family still span the subspace?
I removed one basis vector, but exchanged it for a linearly independent new vector. However, this new vector is not part of my subspace in the first place, so does it still span the subspace?
Any help is greatly appreciated!
Answer: The duals $b_i^*$ span a proper subspace if $V^*$, let's call that $W$. If you replace of of these $b_i^*$ with a vector $a^*\notin W$, then you get a different subspace $W'$ of $V^*$. After all, we clearly have $a^*\in W'\setminus W$ and $b_1^*\in W\setminus W'$. Nevertheless, $\{\,b_i^*\mid i\in I\,\}$ is a basis of $W$, and $\{\,b_i^*\mid i\in I, i\ne 1\,\}\cup \{a^*\}$ is a basis of $W'$. Just note that we still have no linear dependence due to nearly the same finiteness argument.
Comment: Thank you very much! To me it just was not clear that $b_1^* \in W \setminus W'$, but I guess this immediately follows from the finiteness argument as you mentioned :)


Does S3Object.getObjectMetadata() trigger a download of the object?

Question: If I have a S3Object called s3Object and I want to get its metadata like so:
ObjectMetadata objectMetadata = s3Object.getObjectMetadata();

does the call to this function trigger a download of the object from S3?  Or is only the metadata downloaded?  I'm trying to estimate how much data consumption over WiFi or 3G will result from this function call (I'm guessing its on the order of a few bytes if it's only getting the metadata, but obviously much more if it has to download the object).
Answer: Calling .getObjectMetadata makes a HEAD call. It isn't a full GET- in other words, it doesn't get the object itself.
Comment: Does it make a HEAD call for every call on the same object?
Answer: I just wondered this myself, and confirmed with tcpdump that only about 1-2 KB is downloaded for a call to this method.


why does my model fluctuate on validation set and is smooth on the training set?

Question: I use the below architecture in keras for dog-vs-cat dataset
<code>model = models.Sequential()
model.add(layers.Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))
model.add(layers.MaxPool2D((3,3)))
model.add(layers.Conv2D(64,(3,3),activation='relu'))
model.add(layers.MaxPool2D((3,3)))
model.add(layers.Conv2D(128,(3,3),activation='relu'))
model.add(layers.MaxPool2D((3,3)))
model.add(layers.Flatten())
model.add(layers.Dense(512,activation='relu'))
model.add(layers.Dense(1,activation='sigmoid'))
model.compile(optimizer='rmsprop',
             loss='binary_crossentropy',
             metrics=['acc'])
</code>
and got the 85 acc for train and 81 for val_acc
but got the pattern below in validation loss in the end

but my train validation seems to be normal

is my model okey and validation loss is okey?
or did i miss something?
Comment: If you could edit your post so as to explain more of your terms and label your axes, this post will have greater benefit, even for those who don't use the keras library.  Cheers ~
Answer: In many cases, validation set will have much less data in training set. And that is the reason the performance will "fluctuate on validation set and is smooth on the training set".
Think about an extreme case that validation set only have 2 images, if you correctly classify one, then the performance will suddenly jump to 50%.
I have an answer to similar question here
Validation loss decreasing faster than training loss


Expressões regulares postgresql

Question: Fala pessoal, preciso de uma ajuda
Estou tentando fazer uma trigger no postgresql que verifica se o formato de um novo dado a ser inserido em uma tabela está em um determinado formato, no caso, o formato de telefone.
Preciso que o novo telefone a ser inserido esteja no formato +pp(dd)nnnnn-nnnn
Meu problema se encontra na verificação do formato, atualmente está assim NEW.telefone LIKE '^+([^0-9]{2}[^)][^0-9]{5}[^-][^0-9]{4}'
Sou novato com expressões regulares e estou meio perdido, poderiam me ajudar com essa?
Answer: Pessoal consegui solucionar o problema aqui, estava montando a expressão regular de maneira errada, aqui está a maneira correta
NEW.telefone ~ '^\+[0-9]{2}\([0-9]{2}\)[0-9]{5}\-[0-9]{4}$'

Expressões regulares postgresql


How are these negative values understood?

Question: I can't find literature to understand this table.
What I know doing my research is that an effect size should be between 0 and 1. when 0.2 is slow, 0,5 medium and 0.8 and higher , high. But In an article of Cochrane database I found these results and I can't really make a sense of this. I need this really badly so anyone who can help me to understand these values (including those ranges in brackets) I'd really appreciate it.
Comment: It appears that you are looking at Cohen's $d$ as a measure of effect size; at least, your definitions of "low", "medium" and "high" are the ones Cohen proposed for his $d$. As per [Alexis' answer](http://stats.stackexchange.com/a/113521/1352), you can simply flip signs for negative $d$, keeping the interpretation in mind. However, note that $d$ is not constrained to be below 1 - $d>1$ is perfectly possible!
Answer: Assuming the effects you describe as slow [sic], medium and higher are protective effects where patients treated with the drug experience less psychotic outcomes (or side effects or whatever these studies are comparing), a negative value would imply that a patient experienced more psychotic outcomes (or side effects, whatever outcomes, etc.) than placebo... in other words: negative values denote harm, the degree to which they do so is likely inverted from the positive values (e.g. -0.8 and lower is a higher negative effect than >–0.8 to -0.5, etc.).
Of the four rows you show, Aripiprazole appears to be the only drug with confidence bounds (the numbers in the brackets) that are purely negative, implying that it is the only one for which such evidence of negative effect was found. Because the confidence intervals of the other three span zero more or less evenly, you would not say that you had evidence of a positive or negative effect.
If the assumption I stated on the first line of this answer is incorrect, and a higher positive number means a higher bad outcome (say longer psychotic episode, more unwanted side effects, etc. for whatever these studies are about that you are not telling us... hint hint "edit" button in lower left of your question. hint hint :), then the interpretation I just gave is also inverted (i.e. placebo would have higher bad outcomes/drug would have a protective effect).


Calculating and placing values into a second level column in a MultiIndex Pandas DataFrame

Question: I have a multi-indexed DataFrame in which I want to place a level two column named AB. The values of this level two column should equal the AD[1]/DP for each Sample e.g. Sample1 AB = 60/180
import pandas as pd
import numpy as np

genotype_data = [
                    ['0/1', '120,60', 180, 5, '0/1', '200,2', 202, 99],
                    ['0/1', '200,20', 60, 99, '0/1', '200,50', 250, 99],
                    ['0/1', '200,2', 202, 99, '0/1', '200,2', 202, 99]
]

genotype_columns = [['Sample1', 'Sample2'], ['GT', 'AD', 'DP', 'GQ']]
cols = pd.MultiIndex.from_product(genotype_columns)
df = pd.DataFrame(data=genotype_data, columns=cols)

This code produces the following input file/df:
   Sample1                        Sample2
GT      AD   DP  GQ      GT      AD   DP  GQ
0/1  120,60  180   5     0/1   200,2  202  99
0/1  200,20   60   3     0/1  200,50  250  99
0/1   200,2  202  99     0/1   200,2  202  99

The desired result should be:
      Sample1                        Sample2
GT      AD   DP  GQ    AB      GT      AD   DP  GQ    AB
0/1  120,60  180   5  0.33     0/1   200,2  202  99  0.01
0/1  200,20   60   3  0.33     0/1  200,50  250  99  0.20
0/1   200,2  202  99  0.01     0/1   200,2  202  99  0.01

I have come up with a solution to this but it is pretty slow, inefficient and relies on loops. I need a much more efficient solution as I will be performing this on very big files.
def calc_AB(df):

    sam = df.columns.levels[0][0]
    AD = df.xs('AD', level=1, axis=1).unstack().str.split(",", n=2)
    DP = df.xs('DP', level=1, axis=1).unstack()
    AB = round(pd.to_numeric(AD.str[1]) / pd.to_numeric(DP), 2)
    df[sam, 'AB'] = AB.tolist()

    return df

dfs = [calc_AB(df[[sam]].astype(str)) for sam in df.columns.levels[0].tolist()]

pd.concat(dfs, axis=1)

Any help with this would be highly appreciated.
Answer: You need to reorganize the indexes to make sure that there is only one column called 'AD':
df.columns = df.columns.swaplevel(0,1)
stacked = df.stack()
#               AD   DP  GQ   GT
#0 Sample1  120,60  180   5  0/1
#  Sample2   200,2  202  99  0/1
#1 Sample1  200,20   60  99  0/1
#  Sample2  200,50  250  99  0/1
#2 Sample1   200,2  202  99  0/1
#  Sample2   200,2  202  99  0/1

Calculating the new column now is trivial:
stacked['AB'] = stacked['AD'].str.split(',').str[1].astype(int)/stacked['DP']

stacked
#               AD   DP  GQ   GT        AB
#0 Sample1  120,60  180   5  0/1  0.333333
#  Sample2   200,2  202  99  0/1  0.009901
#1 Sample1  200,20   60  99  0/1  0.333333
#  Sample2  200,50  250  99  0/1  0.200000
#2 Sample1   200,2  202  99  0/1  0.009901
#  Sample2   200,2  202  99  0/1  0.009901

You can restore the indexes to whatever they were before if you want.
Comment: I like this use of stack()...  And to unstack  df = stacked.stack().unstack([1,-1]).sort_index()
Comment: After further testing with vary large files, I found it is actually ~8x slower than my solution.
Comment: Surprisingly/unfortunately, this takes the same amount of time to process as my solution. However, it is much cleaner and nicer so I'll use it for now.
Comment: stack / unstack is slow for large dataframes


spamassassin setup how to make sure X-Spam-Status is allways written

Question: I just found out that spamassassin skips checking for email bigger than 250KB by default.
Due to a coding bug, I check for the X-Spam-Status header in incoming emails and did not take into account the fact that it might be null.
I know that I can increase the size of the limit by configuration but it may cause a load issue on my server.
Since I do not want to redeploy my application at this time I was wondering if there is a way to make sure this header exists automatically in every email, either by spamassassin configuration or by postfix or something else.
Thanks,
Dov.
Answer: As you mentioned, it is the "default" setting with spamassasin that it won't scan messages which are bigger than the default/configured size. Without passing the mails through spamd, the "X-Spam-Status" header is not going to be added to the mail, unless you add the header manually to the mail if it is not already present. You can use a pre-processing script to check the header and add it, if the header is not present and then pass that to your application.
Cheers
Answer: Such a setup violates the principles of:

KISS
Be liberal in what you accept

You'll be much farther ahead fixing your application rather than relying upon yet another independent piece of code or configuration that you'll need to maintain. Do it the right way.


Add/Remove User Role on Node View

Question: I want to be able to add and remove a role to a user via a simple click of a button on almost any node. (Specifically the plan is to allow a user to give themselves a role that would give them extra editing powers, but so that they can remove it when generally browsing the site so all the editing options don't clog up the UI).
The best method I could think of for this is to have two nodes, and set up a rule so visiting these nodes added or removed the user role. I could then create simple menu links that linked to these nodes.
Essentially what I have set up is one rule which goes:
Event: Content is Viewed
Condition: Node is of alias - node url
Action: Add user role - Edit Powers

This rule works fine. When the node is visited the role is added to the user. However the reverse rule doesn't work despite being nearly identical to the other. It reads:
Event: Content is viewed
Conidtion: Node is of alias - node url
Action: Remove user role - Edit Powers

However visiting this URL doesn't remove the user role. The question here is two-fold.
a) Why would the rule not be working, and why can't it remove a role from the user?
b) Is this a really complex way of achieving something that might be quite simple? At the moment I assume this rule is effectively being checked when any user visits any page, which I'm sure isn't great from a resource point of view - but I couldn't think of an easier way to do it with flags etc. So please do advise if there is an easier way.
Thanks in advance for any help.
Answer: Try creating a condition that the user have the role, before trying to remove it.
Also, you could look into Rules Link - you may be able to add it to a custom Profile Page, allowing the user to access and change their settings via My Account - at least from a UI standpoint it might make more sense.
Answer: There are two ways I can think of doing this.

Install and Enable Roles Assign Module. Once this module is enabled the user can go to his account and then assign roles(A subset selected by the admin) or remove them from his account.
Install Flag module. Create one flag for each of the roles. This will give you Add/remove flag options and your can integrate it with Flag actions to assign or remove the Roles.
Comment: I had considered the flags options. The reason I dismissed it - is to my knowledge you can't set, effectively, a global flag. In other words if you made the flag appear on nodes it would only change on a specific node if flagged, not all nodes. If a flag could be added as a sort of generic button to blocks that would be great, but don't think you can do that.
Answer: In the condition "Node is of alias", what have you entered? It might be wrong. Post it here to help you if you want.
Comment: I posted the actual relative node url, in this case:

node/119 & node/120. Thanks for your help.
Comment: Download this module [https://www.drupal.org/project/pathrules] and use that for your condition. I think this is your problem. You are providing the node path instead of the node alias. The module above will provide a new condition that checks the path instead of the path alias. Waiting for your feedback.

Add/Remove User Role on Node View