Imagem não aparece na table JSP

Question: Gravei no meu banco de dados uma imagem em que fiz o upload dela na minha página HTML. Ele salva a imagem em bytes no meu banco de dados, mas ao mostrar ela em uma tabela, ela não aparece.
UPDATE
Minha HTML no meu JSP:

Lista de Produtos Cadastrados

          Codigo
          Produto
           Nome
           Descricao
           Valor
           Marca
           Tamanho
           Parcelas
          Tecido

      <c:forEach items="${requestScope.produtos}" var="registro">

               <c:out value="${registro.codigo}"/>
               <img src="<c:url value="/produto/imagens=?id=${registro.codigo}"/>"
               <c:out value="${registro.nome}"/>
               <c:out value="${registro.descricao}"/>
               <c:out value="${registro.valor}"/>
               <c:out value="${registro.marca}"/>
               <c:out value="${registro.tamanho}"/>
               <c:out value="${registro.parcelas}"/>
               <c:out value="${registro.tecido}"/>

      </c:forEach>

Ao cadastrar os produtos corretamente, é redirecionada para a servlet @WebServlet(urlPatterns = {"/produtos/listar"}) que a servlet redireciona para pagina de CadastroProdutos que contem a table que ira mostrar os dados.
São apresentados todos os dados menos a imagem cadastrada
Minha Pagina de Cadastro de Produtos que contem a table que ira mostrar os dados.

Minha Servlet responsavel pelo cadastro
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int id = 0;
    String nome = request.getParameter("nome");
    String descricao = request.getParameter("descricao");
    double valor = Double.parseDouble(request.getParameter("valor"));
    String marca = request.getParameter("marca");
    String tamanho = request.getParameter("tamanho");
    int parcelas = Integer.parseInt(request.getParameter("parcelas"));
    String tecido = request.getParameter("tecido");

    Part imagePart = request.getPart("file");
    String tipo = getFileType(imagePart);
    byte[] conteudo = imagePart == null ? new byte[0] : getBytesFromInputStream(imagePart.getInputStream());

    Produtos p = new Produtos(id, nome, descricao, valor, marca, tamanho, parcelas, tecido);
    ImagemProdutos im = new ImagemProdutos(tipo, conteudo);

    ProdutosDAO.instancia().salvar(p, im);

    RequestDispatcher dispatcher = request.getRequestDispatcher("/produtos/listar");
    dispatcher.forward(request, response);

}

Minha servlet responsavel por listar os dados
 @WebServlet(urlPatterns = {"/produtos/listar"})
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

     try {
        List<Produtos> produtos = ProdutosDAO.instancia().listarTodos();
        request.setAttribute("produtos", produtos);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/CadastroProdutos.jsp");
        dispatcher.forward(request, response);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ListarProdutos.class.getName()).log(Level.SEVERE, null, ex);
    }

}

Mina Servlet responsável por mostrar a imagem
 @WebServlet(urlPatterns = {"/produto/imagens"})
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //a imagem deve ser eniada por url, em uma servlet separada propria

    try {
        int id = Integer.parseInt(request.getParameter("id"));
        Model.ImagemProdutos ip = ProdutosDAO.instancia().lerImagem(id);
        response.setContentType("image/" + ip.getFormato());
        response.getOutputStream().write(ip.getConteudo());

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ImagemProdutosServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Comment: Não deixe o seu método `Conecta.conexao()` lançar esse `ClassNotFoundException` e nem o seu DAO conhecer isso. Dê uma olhada [**aqui**](https://pt.stackoverflow.com/a/242765/132) para ver como fazer isso. Além disso, acabei de testar o servlet da imagem isoladamente e funcionou: https://pastebin.com/AgPA7MXs
Comment: porque quando eu debugo isoladamente a servlet da imagem ele da null no  int id = Integer.parseInt(request.getParameter("id"));
Comment: ela da null por que quando eu abro a pagina CadastroPrdutos.jsp ele não mostra nenhum dado na table assim ele não envia o  "
Comment: Tem um `=` a mais na URL que está no JSP. O `=` que está imediatamente antes do `?` não deveria estar lá.
Comment: eu acho Victor Stafusa que o erro ocorre aqui    porque quando abro a pagina de CadastroProdutos.jsp ele não me retorna nenhum dado na tabela
Comment: ele só aparece os dados na table mas sem a imagem,após eu inserir um dado
Comment: A JSP só vai listar os dados se você acessá-la por meio do servlet `/produtos/listar`. Se você acessá-la diretamente, ela não vai encontrar os produtos porque eles são colocados dentro do `request` pela servlet.
Comment: Tentei com isso: https://pastebin.com/K5HjF1vr - Criei dois arquivos na pasta `C:\Projetos`: `setas1.png` e `setas2.png`. Quando acesso `http://localhost:8080/Imagens/produto/imagens=?id=1`, ele abre o `setas1.png`. Quando acesso o `http://localhost:8080/Imagens/produto/imagens=?id=2`, ele abre o `setas2.png`.
Comment: entendi Victor Stafusa
Answer: Onde está o seu problema
O problema está aqui:
<img src="<%=registro.getImagem()%>" width="100" height="100" />

Você não mostrou como é o método getImagem() da sua classe Produtos, mas ao olhar para isso, dá para crer que ele retorne um array de bytes:
pro.setImagem(rs.getBytes("prod_imagem"));

O problema é que no HTML, a tag src serve para dizer qual é URL de onde a imagem pode ser baixada, e não para dar a sequência de bytes que correspondem a imagem.
Tipo da imagem
Há ainda o problema que você não especifica o tipo da imagem. Vamos supor que possa ser "png", "jpeg" ou "gif" (em minúsculas). Adicione os métodos getFormatoImagem() e setFormatoImagem(String) na classe Produtos (além de um campo private String tipoImagem) e uma coluna prod_tipo_imagem na tabela tb_produtos do banco de dados. Caso o tipo daa imagem seja sempe o mesmo (por exemplo, todas elas forem "png"), isso não é necessário.
Tendo então um campo para o tipo da imagem, há pelo menos duas abordagens possíveis. A primeira seria utilizar uma data-uri em base-64 e a outra é com um servlet de imagens.
A abordagem com data-uri
Você colocaria dessa forma:
<img src="data:image/<%=registro.getFormatoImagem()%>;base64,<%=new String(java.util.Base64.getUrlEncoder().encode(registro.getProd_codigo()))%>" width="100" height="100" />

Se a imagem for de um tipo fixo, você pode substituir o <%=registro.getFormatoImagem()%> pelo tipo dela (ex: "png").
Entretanto, essa abordagem não é muito vantajosa para imagens grandes ou muito numerosas, pois deixa o carregamento da página bem pesado. Por isso, vamos ver a outra abordagem.
Servlet de imagens
Imagens são carregadas por meio de URLs. Então a solução seria dar uma URL para a imagem:
<img src="<%=request.getLocalName()%>:<%=request.getLocalPort()%>/images?id=<%=registro.getProd_codigo()%>" width="100" height="100" />

E então você tem que colocar um servlet para disponibilizar a resposta em bytes. Algo parecido com isso (supondo que você esteja usando Servlets 3.0 ou superior):
import java.io.IOException;
import javax.servlet.HttpServlet;
import javax.servlet.HttpServletRequest;
import javax.servlet.HttpServletResponse;
import javax.servlet.WebServlet;

@WebServlet(urlPatterns = {"/produto/imagens"})
public class ImagemServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException
    {
        int id = Integer.parseInt(request.getParameter("id"));
        ProdutosDAO dao = new ProdutosDAO();
        Produtos p = dao.mostrarProduto(id);
        response.setContentType("image/" + p.getFormatoImagem());
        response.getOutputStream().write(p.getImagem());
    }
}

Se o formato da imagem for fixo, você usaria response.setContentType("image/png");, por exemplo.
Revendo o código da classe Produtos
Observe que você carrega os produtos junto com as suas imagens. Porém, carregar os bytes da imagem é algo pesado em termos de IO, de processamento e de memória. Além disso, ao montar uma instância de Produtos, apenas em alguns poucos casos você vai estar interessado em carregar os bytes da imagem. Em especial, se você fizer uma lista de produtos e encher ela com as imagens, vai estourar a memória do servidor facilmente. Agora que temos uma abordagem que trás as imagens separadamente do resto do conteúdo dos produtos, podemos separá-las.
O Java tem convenções de código que é muito recomendável de serem seguidas. Isso significa que nomes como setProd_desc estão fora do padrão, o padrão seria setProdutoDescricao. Aliás, se a classe se chama Produtos, então o Produto no nome do método é redundante, e setDescricao já seria o bastante. Uma outra observação é que o nome da classe deveria estar no singular e não no plural.
Classes imutáveis são mais fáceis de se trabalhar do que classe mutáveis, e a sua classe Produto é uma boa candidata a uma dessas. Além disso, é uma boa prática que o construtor retorne um objeto já devidamente fabricado ao invés de um esqueleto a ser consertado depois ao chamar-se um monte de setters.
Considerando-se isso, assim ficam as suas classes:
public final class Produto {
    private final int codigo;
    private final String nome;
    private final String descricao;
    private final double valor;
    private final String marca;
    private final String tamanho;
    private final int parcelas;
    private final String tecido;

    public Produto(
            int codigo,
            String nome,
            String descricao,
            double valor,
            String marca,
            String tamanho,
            int parcelas,
            String tecido)
    {
        this.codigo = codigo;
        this.nome = nome;
        this.descricao = descricao;
        this.valor = valor;
        this.marca = marca;
        this.tamanho = tamanho;
        this.parcelas = parcelas;
        this.tecido = tecido;
    }

    public int getCodigo() {
        return codigo;
    }

    public String getNome() {
        return nome;
    }

    public String getDescricao() {
        return descricao;
    }

    public String getValor() {
        return valor;
    }

    public String getMarca() {
        return marca;
    }

    public String getTamanho() {
        return tamanho;
    }

    public int getParcelas() {
        return parcelas;
    }

    public String getTecido() {
        return tecido;
    }
}

public final class ImagemProduto {
    private final String formato;
    private final byte[] conteudo;

    public ImagemProduto(String formato, byte[] conteudo) {
        this.formato = formato;
        this.conteudo = conteudo;
    }

    public String getFormato() {
        return formato;
    }

    public byte[] getConteudo() {
        return conteudo;
    }
}

Revendo o código da classe ProdutosDAO
A sua classe ProdutosDAO também precisa de revisão.
Em primeiro lugar, usar o try-with-resources é altamente recomendável para ter certeza de que você está fechando os recursos abertos adequadamente, além de não ter que ficar quebrando a cabeça escrevendo código chato para fazer esse tipo de trabalho.
Em segundo lugar, use os tipos genéricos adequados.
Em terceiro lugar, não use JOptionPane no DAO. O JOptionPane vai mostrar uma telinha de erro no servidor, onde ninguém estará olhando, e não no lado do cliente. Além disso, isso é uma violação do padrão MVC.
Em quarto lugar, diferentes instâncias de ProdutoDAO não são distinguíveis e têm todas o mesmo comportamento. Assim sendo, nem tem sentido haver mais de uma instância, e por isso podemos usar o padrão singleton:
Assim sendo, vamos re-elaborar o seu DAO, considerando a classe Conecta que você referenciou nessa outra pergunta sua:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProdutoDAO {

    private static final String LISTAR_SQL = "SELECT prod_cod, prod_nome, prod_desc, prod_valor, prod_marca, prod_tamanho, prod_parcelas, prod_tecido FROM tb_produtos";

    private static final String POR_ID_SQL = "SELECT prod_cod, prod_nome, prod_desc, prod_valor, prod_marca, prod_tamanho, prod_parcelas, prod_tecido FROM tb_produtos WHERE cod_prod = ?";

    private static final String IMAGEM_SQL = "SELECT prod_tipo_imagem, prod_imagem FROM tb_produtos WHERE prod_cod = ?";

    private static final String INSERT_SQL = "INSERT INTO tb_produtos (prod_cod, prod_nome, prod_desc, prod_valor, prod_marca, prod_tamanho, prod_parcelas, prod_tecido, prod_tipo_imagem, prod_imagem) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    private static final ProdutoDAO singleton = new ProdutoDAO();

    private ProdutoDAO() {
    }

    public static ProdutoDAO instancia() {
         return singleton;
    }

    private Produto lerProduto(ResultSet rs) throws SQLException {
        int codigo = rs.getInt("prod_cod");
        String nome = rs.getString("prod_nome");
        String descricao = rs.getString("prod_desc");
        double valor = rs.getDouble("prod_valor");
        String marca = rs.getString("prod_marca");
        String tamanho = rs.getString("prod_tamanho");
        int parcelas = rs.getInt("prod_parcelas");
        String tecido = rs.getString("prod_tecido");
        return new Produto(codigo, nome, descricao, valor, marca, tamanho, parcelas, tecido);
    }

    private ImagemProduto lerImagem(ResultSet rs) throws SQLException {
        String tipo = rs.getString("prod_tipo_imagem");
        byte[] conteudo = rs.getBytes("prod_imagem");
        return new ImagemProduto(tipo, conteudo);
    }

    public List<Produto> listarTodos() {
        try (
            Connection con = Conecta.conexao();
            PreparedStatement ps = con.prepareStatement(LISTAR_SQL);
            ResultSet rs = ps.executeQuery();
        ) {
            List<Produto> lista = new ArrayList<>();
            while (rs.next()) {
                lista.add(lerProduto(rs));
            }
            return lista;
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    public Produto lerProduto(int idProduto) {
        try (
            Connection con = Conecta.conexao();
            PreparedStatement ps = con.prepareStatement(POR_ID_SQL);
        ) {
            ps.setParameter(1, idProduto);
            try (ResultSet rs = ps.executeQuery()) {
                return lerProduto(rs);
            }
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    public ImagemProduto lerImagem(int idProduto) {
        try (
            Connection con = Conecta.conexao();
            PreparedStatement ps = con.prepareStatement(IMAGEM_SQL);
        ) {
            ps.setParameter(1, idProduto);
            try (ResultSet rs = ps.executeQuery()) {
                return lerImagemProduto(rs);
            }
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    public void salvar(Produto pro, ImagemProduto im) {
        try (
            Connection con = Conecta.conexao();
            PreparedStatement ps = con.prepareStatement(INSERT_SQL);
        ) {
            ps.setInt(1, pro.getCodigo());
            ps.setString(2, pro.getNome());
            ps.setString(3, pro.getDescricao());
            ps.setDouble(4, pro.getValor());
            ps.setString(5, pro.getMarca());
            ps.setString(6, pro.getTamanho());
            ps.setInt(7, pro.getParcelas());
            ps.setString(8, pro.getTecido());
            ps.setString(9, im.getFormato());
            ps.setBytes(10, im.getConteudo());
            ps.execute();
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }
}

Observe que como você não especificou o que há na classe Conecta, mas decerto há coisas a melhorar nela.
Por fim, vamos aplicar as mudanças na nossa classe ImagemServlet:
import java.io.IOException;
import javax.servlet.WebServlet;
import javax.servlet.HttpServlet;
import javax.servlet.HttpServletRequest;
import javax.servlet.HttpServletResponse;

@WebServlet(urlPatterns = {"/produto/imagens"})
public class ImagemServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException
    {
        int id = Integer.parseInt(request.getParameter("id"));
        ImagemProduto ip = ProdutoDAO.instancia().lerImagem(id);
        response.setContentType("image/" + ip.getFormato());
        response.getOutputStream().write(ip.getConteudo());
    }
}

Definindo as servlets
Scriptlets são considerados odiados, ultrapassados e obsoletos. Misturar código Java enxertado em pedaços de HTML é uma coisa horrorosa a se fazer, e esse é um dos vários motivos pelo qual scriptlets devem ser abandonados. Além disso, o uso de scriptlets tende a levar a uma violação do padrão MVC.
O primeiro passo para eliminar os scriptlets é separar o comportamento em servlets para não ficar misturado com o JSP:
import java.io.IOException;
import javax.servlet.HttpServlet;
import javax.servlet.HttpServletRequest;
import javax.servlet.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.WebServlet;

@WebServlet(urlPatterns = {"/produto/listar"})
public class ListagemProdutoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        List<Produto> produtos = ProdutoDAO.instancia().listarTodos();
        request.setAttribute("produtos", produtos);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/produtos.jsp");
        dispatcher.forward(request, response);
    }
}

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import javax.servlet.HttpServlet;
import javax.servlet.HttpServletRequest;
import javax.servlet.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.WebServlet;

@WebServlet(urlPatterns = {"/produto/salvar"})
@MultipartConfig
public class SalvarProdutoServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        int id = Integer.parseInt(request.getParameter("id"));
        String nome = request.getParameter("nome");
        String descricao = request.getParameter("descricao");
        double valor = Double.parseDouble(request.getParameter("valor"));
        String marca = request.getParameter("marca");
        String tamanho = request.getParameter("tamanho");
        int parcelas = Integer.parseInt(request.getParameter("parcelas"));
        String tecido = request.getParameter("tecido");

        Part imagePart = request.getPart("imagem");
        String tipo = getFileType(imagePart);
        byte[] conteudo = imagePart == null ? new byte[0] : getBytesFromInputStream(imagePart.getInputStream());

        Produto p = new Produto(id, nome, descricao, valor, marca, tamanho, parcelas, tecido);
        ImagemProduto im = new ImagemProduto(tipo, conteudo);

        ProdutoDAO.instancia().salvar(p, im);

        RequestDispatcher dispatcher = request.getRequestDispatcher("/produtos/listar");
        dispatcher.forward(request, response);
    }

    private String getFileType(Part part) {
        if (part == null) return "";
        String partHeader = part.getHeader("content-disposition");
        for (String content : partHeader.split(";")) {
            String trimmedContent = content.trim();
            if (trimmedContent.startsWith("filename")) {
                String nomeEntreAspas = trimmedContent.substring(trimmedContent.indexOf('=') + 1);
                String nomeDoArquivo = nomeEntreAspas.trim().replace("\"", "");
                String extensao = nomeDoArquivo.substring(nomeDoArquivo.indexOf('.') + 1);
                return extensao;
            }
        }
        return null;
    }

    public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 1024];

        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }

        return os.toByteArray();
    }
}

O servlet ListagemProdutoServlet usa o DAO para ler a lista de produtos (sem as imagens, vez que essas são lidas no ImagemServlet) e colocar a lista lida na requisição. Em seguida, ele redireciona para o JSP produtos.jsp.
Já o servet SalvarProdutoServlet usa o DAO para salvar o produto e redireciona para o ListagemProdutoServlet que irá ler a lista de produtos e redirecionar ao produtos.jsp. O SalvarProdutoServlet é um servlet multipart (veja mais sobre isso aqui).
O método getBytesFromInputStream é o responsável por ler um InputStream por completo (que corresponde ao arquivo submetido) e com isso fornecer um array de bytes que contém o conteúdo do arquivo. Peguei ele desta resposta do SOen.
Se/quando você começar a usar o Java 9, a parte do getBytesFromInputStream(imagePart.getInputStream()) poderia/poderá ser substituída por imagePart.getInputStream().readAllBytes(), e com isso o método getBytesFromInputStream(InputStream) tornar-se-ia desnecessário. Com o novo método readAllBytes() do Java 9, poderíamos pegar o conteúdo inteiro do arquivo enviado de uma forma mais simples.
Você ainda vai precisar alterar o SalvarProdutoServlet para verificar se todos os dados que deveriam ser passados estão presentes e se foram preenchidos de forma válida antes de realizar a inserção no DAO de fato.
Revisando o código da sua JSP
Supondo que a sua JSP seja a página produtos.jsp a qual me referi, agora que já temos a lógica de acesso ao banco de dados dentro de servlets, só resta ao JSP a exibição dos dados.
Com o uso de JSTL e de EL, podemos então enfim eliminar todos os scriptlets. Eis o código resultante:
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

        <meta charset="UTF-8">
        <title>Listagem de produtos</title>

        <form action="<c:url value="/produto/salvar" />" method="POST" enctype="multipart/form-data">

Cadastro de Produtos

                        Nome do produto: <input type="text" id="nome" name="nome" />

                        Descrição: <input type="text" id="descricao" name="descricao" />

                        Valor: <input type="text" id="valor" name="valor" />

                        Marca: <input type="text" id="marca" name="marca" />

                        Tamanho: <input type="text" id="tamanho" name="tamanho" />

                        Parcelas: <input type="text" id="parcelas" name="parcelas" />

                        Tecido: <input type="text" id="tecido" name="tecido" />

                        Código: <input type="text" name="codigo" id="codigo" />

                        Arquivo: <input type="file" name="imagem" id="imagem"/>

                        <input type="submit" value="Cadastrar" />

        </form>

Lista de Produtos Cadastrados

                Código
                Foto
                Nome
                Descrição
                Valor
                Marca
                Tamanho
                Parcelas
                Tecido

            <c:forEach items="${requestScope.produtos}" var="registro">

                    <c:out value="${registro.codigo}" />
                    <img src="<c:url value="/produto/imagens?id=${registro.codigo}" />"
                    <c:out value="${registro.nome}" />
                    <c:out value="${registro.descricao}" />
                    <c:out value="${registro.valor}" />
                    <c:out value="${registro.marca}" />
                    <c:out value="${registro.tamanho}" />
                    <c:out value="${registro.parcelas}" />
                    <c:out value="${registro.tecido}" />

            </c:forEach>

Comment: Victor Stafusa obrigado por responder,coloquei o código que você postou mas aconteceu um erro na minha servlet que faz o cadastro dos produtos um cannot find symbol symbol:method readAllBytes() location: class InputStream, coloquei um UPDATE na pergunta e coloquei a linha e a causa do erro
Comment: @User1999 Qual é a versão do seu Java?
Comment: Uso o NetBeans IDE 8.2
Comment: @User1999 NetBeans é a sua IDE. O Java é independente do NetBeans. O NetBeans pode trabalhar com qualquer versão do Java. Entretanto, vou supor que você está no Java 8. Esse método aí foi acrescentado no Java 9, por isso que você não consegue usá-lo.
Comment: e agora como faço para ler  byte[] conteudo?
Comment: @User1999 Resposta editada. Acrescentei um método `getBytesFromInputStream(InputStream)` para fazer isso.
Comment: Victor Stafusa ocorreu um erro ao cadastrar o produto no banco de dados ao debugar o código do cadastro dos produtos na minha Servlet e passar o breakpoint na linha String tipo = getFileType(imagePart); ele lança um erro, editei minha pergunta e coloquei o código e o stack trace completo do erro
Comment: ele lança o erro java.lang.StringIndexOutOfBoundsException: String index out of range: -1
java.lang.String.substring(String.java:1927)
Controler.CadastroProdutos2.getFileType(CadastroProdutos2.java:124)
Controler.CadastroProdutos2.doPost(CadastroProdutos2.java:100)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728) na linha 124 do getFileContent
Comment: @User1999 Qual é o nome do arquivo que você tentou fazer o upload?
Comment: @User1999 Editei a resposta e alterei a linha onde o erro ocorre. Agora funciona?
Comment: Victor salvou os dados corretamente, mas agora o problema é outro, Ao cadastrar os produtos corretamente, é redirecionada para a servlet @WebServlet(urlPatterns = {"/produtos/listar"}) que essa servlet redireciona para pagina de CadastroProdutos que contem a table que ira mostrar os dados. São apresentados todos os dados menos a imagem Atualizei a pergunta e coloquei o código e a imagem do erro

Imagem não aparece na table JSP


Mean and variance for unequal samples

Question: I have a sampling of variable sized plots. Each plot contains the number of trees present on the plot. Given:

$n=$ the number of plots
$s_i=$ the size of the $i^{th}$ plot
$y_i=$ the number of trees on the $i^{th}$ plot

What method should I use to determine the mean and the variance of the sample?
Because the plots are variable sized, I'm hesitant to use the standard mean and variance formulas. My intuition tells me that larger plots should be weighted more than smaller ones.
A colleague of mine has suggested to use the density of each plot as the sampling statistic and the average of the densities as the mean to calculate variance using the standard variance formula. In my opinion this method weights smaller plots equal to larger plots, thus in effect giving smaller plots more weight.
I'm not a statistician, but an idea I had was to weight each plot by the number of averaged sized plots in the sample and to inversely weight the number of trees sampled, then use the weighted average formula to calculate the mean and the weighted sample variance formula for frequency based weights to calculate the variance. E.g.,
\begin{align}
w_i &= \frac{s_i}{\bar{s}}  \\
\ \\
x_i &= y_i\frac{\bar{s}}{s_i}  \\
\ \\
\bar{x} &= \frac{\sum{w_ix_i}}{\sum{w_i}}  \\
\ \\
s^2 &= \frac{w_i(x_i-\bar{x})^2}{n-1}
\end{align}
It should be noted that: $w_ix_i=y_i$ and $\sum{w_i}=n$ thus $\bar{x}=\bar{y}$ where $\bar{y}$ is the number of trees for an averaged sized plot.
Is this method statistically valid or is there another formula I should be using?
Comment: It looks like you are doing a version of FIREMON sampling ((frames.gov/partner-sites/firemon/sampling-methods)). I've little knowledge of that method.  However the process of "simple random sampling", with or without replacement, requires that the population consist of  $N$ identifiable plots, from which $n$ are chosen.
Comment: Some questions:  When you say a "sampling" of plots, what do you mean? _Exactly_ how were the plots selected for study? Were they a random sample _of some kind_ from a target population of trees?  If yes, is the mean you are estimating supposed to estimate the mean of that population?  If no, then exactly what target parameter are you trying to estimate?
Comment: The plots are randomly selected from the population. The goal is to estimate the number of trees in the population based upon the sample and state the associated standard error of that estimate. There are two ways to calculate this value.
Comment: 1. Assume the density of the sample represents the density of the population. Eg: total_area * number_of_trees_sampled / area_sampled

2. Calculate the total number of averaged sized plots in the population area and multiply it by the total number of trees per averaged sized plot (total_area / average_plot_size) * (number_of_trees_sampled / number of samples)

Both are essentially the same. Eq2 = Eq1
Comment: Just two more questions: 1) When you say "randomly selected"; do you mean a "simple random sample (without replacement)", where each plot had the same chance of selection, or something else? 2) Can you categorize the sizes of the plots in the population? That would make it possible to "post-stratify" the sizes of tghe sampled plots.
Comment: 1) simple random with replacement. A random point for each plot is chosen within the population area and designated as the center of the plot.

2) It's hard to categorize the size of a plot. The majority of the plots should all be of the same size, but it's hard to enforce that constraint if the user of our software generates additional plots at a later time.

3) To complicate things, a user may choose to only sample a portion of a plot due to physical limitations. Eg: the plot overlaps the boundary of the study area (Note: I realize this causes bias, but it has been done this way for years)
Answer: It looks like you are doing a version of FIREMON sampling (https://www.frames.gov/partner-sites/firemon/sampling-methods/). I know little about such point smpling, and I think you would benefit from consultation with someone knowledgeable about such methods. I'll give you my best guess, but I could be wrong.
I recommend a ratio estimate of the total number of trees. Larger plots are automatically represented in proportion to their size.
Denote $s_i$ = area for plot $i$ and $y_i$ = the number of trees in the plot.  $S$ and $Y$ are the totals in the population. You know $S$ and want to estimate $Y$.  The average density in the population is:
$$
R = \frac{Y}{S}
$$
You know the total area in the population is $S$. So the number of trees in the population $Y$ obeys the equation:
$$
Y = R\,S
$$
The sample will permit you to estimate $R$, so that your estimated total will be:
$$
\hat{Y}_R = \hat{R} S
$$
The natural estimate of $R$ is the ratio of sample totals, which is the same as the ratio of sample means for number of trees and area:
$$
\hat{R} = \frac{y}{s} = \frac{\overline{y}}{\overline{s}}
$$
Calculation of estimated Standard Error
Methods for estimating the standard error include: linearization, the jackknife, and the bootstrap.  All are presented in standard sampling texts. I'll present the linearization method, which requires a "large" n.
(Cochran, 1977, pp; 32; 160-163).
The  approximate standard error of $\hat{Y}_R$  under sampling with replacement is (Cochran, 1977, $v_2$, page 155):
\begin{equation}
SE(\hat{Y}_R) =  S\sqrt{\frac{\sum_{i=1}^n  (y_i - \hat{R}s_i)^2}{n(n-1) \overline{s}^2}}
\end{equation}
If, in fact, the process is not "simple random sampling" of plots (see my comment), then this might still be valid.  I would speculate that for the point sampling method, one could multiply the standard error above by  a "finite population correction" $\sqrt{1-{\dfrac{s}{S}}}$.
References
Cochran, William G. 1977. Sampling techniques. New York: Wiley.
Comment: Thank you for the excellent response. A quick comparison of this method against the standard variance formula shows that if all the plots are the same size then it converges appropriately. Once it has been peer reviewed, I'll mark it as the accepted solution if it's found acceptable.

Mean and variance for unequal samples


Good ways to work with forms in node and express

Question: Being new to node js and express has me wondering the best ways to get things done. Are there any specific conventions used in working with forms?
Comment: This is a pretty vague question. You should really ask more specific technical questions here.
Answer: I use express-validator to validate input fields.
Here's an example:
app.post('/login', routes.login.post);

//routes/login.js

exports.login.post = function(req, res){
  req.assert('username', 'Enter username').notEmpty();
  req.assert('password', 'Enter password').notEmpty();
  res.locals.err = req.validationErrors(true);

  if ( res.locals.err ) {
    if ( req.xhr ) {
      res.send(401, { err: res.locals.err });
    } else {
      res.render('login');
    }

    return;
  }

  //authenticate and set user in session here
};

Comment: Ok. Thanks. Hopefully it will help
Answer: I strongly recommend you to pass all of your forms' data via any kind of XSS attacks or other injections filter. For example, you may use node-validator
It's rather simple to use. To filter XSS injections, just write:
req.sanitize('textarea').xss();

etc. More docs can be found here: node-validator
Comment: Thanks. Almost forgot about this. Would it also be necessary to escape script tags
Comment: express-validator relies on node-validator.


Transposing a complete piece

Question: I am quite confused about transposing from one key to another. I have got an orchestral piece in C major and I would like to change it to e minor. The harmony has plenty of chromatic chords. How should I proceed? From CM to em there is four semitones; should I move all notes a perfect third and then fix any pitch that do not belong to target key?
Comment: Generally, transposing means changing from one key to another. najor to major, or minor to minor.
Comment: I think the word you're looking for is "transcribe", not "transpose". You want to basically rewrite it in an entirely different key.
Answer: You cannot directly transpose from a major key to a minor key.  It will need a degree of re-writing. Particularly where there are chromatic chords.
Comment: @FrankGarcía First of all, thirds cannot be perfect. Only unisons, fourths, fifths, and octaves can be perfect. Second of all, if you move the whole song by the same interval, no matter what it is, you will never change the song from major to minor.
Comment: I think you have just explained the issue perfectly!
Comment: Right now I have seen some lessons online about transposing a melodic line from one key to another; a melody chromatically transposed following a specific numbers of semitones. If my piece is in C major and I want it in E minor, Is it wrong to move all notes a perfect third up? Thank you very much.
Comment: ...I have just realized that I am wrong : (
Comment: Do you know any book that explain this issue?
Comment: He did, Laurance. My question was for you. Anyway, if I have understood something; a piece can be transposed from major to major, and from minor to minor, but transposing from major to minor one should do something that requires a degree of re-writing...seriously? son complex is the issue? To learn which scales degree have to be flattered and...what else? thank you for your answers : )
Answer: E minor is relative to G major, so you could also move it up seven half steps and then reharmonize. For example, if you had a C chord (C,E,G) you could change the G to an A and have an a minor chord that still shared two common tones.
Also, thirds are either major or minor, not perfect. You refer to a major third. But if you took it to G major instead, that would be a perfect fifth. Perfect intervals invert to perfect intervals (5ths to 4ths, and 8ths to 1sons), whereas major intervals invert to minor intervals.
Comment: `if you had a C chord (C,E,G) you could change the G to an A and have an a minor chord` this is true, but if you want to transpose the piece to G major (or its relative scale E minor), the C chord would have to turn into a G major chord, not a A minor one.
Comment: you are right of course-- my example was referring just to the local operation of reharmonizing a particular chord (for example C as the IV chord of G becoming a the ii), not the compound operation of transposition and reharmonization, which in your example C would transpose to G and then reharmonize to e.
Answer: Your idea is correct. You move all notes the same number of semitones. Then figure out what key this will be. There are two possible problems. First, the new key may cause notes to be out of range for a given instrument (considering a human voice an instrument.) This m ay require some re-orchestration or trying another target key. Second, the tessitura may move in a way that makes some chord voicings sound squeaky or muddy; some rearrangement of inner voices may be required
Comment: It simply doesn't work in a lot of cases. It will work in pieces that are very basic, with I, IV and V only, but include chromatics and the 3 minor harmonies, and it's all but impossible to do it as simply as you allude.
Comment: While a perfectly reasonable answer about transposition generally, this doesn't address the specific problem in the question of "transposing" from a major key to a minor key.
Comment: Specifically, C major to E *minor*. Perhaps you thought it was E *major*?
Comment: Same problems. Move the notes. Adapt the chords. (I wrote somewhere else how to convert major to minor and vice versa).  I swaps with i, IV with iv, V with v non cadence and V with V cadence, iii with III, v00 stays the same, VII applied to correct voice leading, ii swaps with ii0, vi with VI. Sevenths and inversions as needed (usually same as original). Neapolitan, German, French, and Italian Sixths stay the same. Diminished and augmented chords mostly stay the same. Voice leading has to be adapted to avoid the usual mistakes.

Transposing a complete piece


How are samples selected when batching?

Question: Suppose after being randomized samples in a dataset can be written $\{x_i\}_{i = 0}^n$ and are put into a batch for mini-batch gradient descent. Are the samples drawn randomly into a batch, or are the batches like a sliding window of size batch size, such that if the batch size is 32, then for the first batch samples $\{x_i\}_{i = 0}^{31}$ are used, we take a step towards the loss function's global minimum, then for the second samples $\{x_i\}_{i = 32}^{64}$ samples are used, another step, and so on. For the last batch, samples $\{x_i\}_{i = n-32}^{n}$ are used. Once $n$ samples are used, the dataset has ran through a full epoch, the samples are randomized again, and the process is repeated.
Is this the correct way of thinking about how the mini-batch GD process works, or is it gone about a different way, like randomly sampling 32 samples each time?
What happens differently when replacement is allowed?
Answer: Yes, one way to think about it is what you described. Another way is: the samples are randomly sorted, then the first 32 are taken, next 32 and so on. Once the epoch is complete, they are randomly sorted and the first 32 are selected, and basically the process repeats.
In some variations replacement is allowed, but most of the time it is not, as far as I know.
Comment: How is what you described different from what I detailed? That sound exactly like what I just described. What happens when replacement is allowed?
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: It isn't different, it is what you described. When replacement is allowed, then the first batch might be $\{x_i\}_{i=0}^{31}$ and the second batch could contain elements from the first batch, for example, $\{x_i\}_{i=27}^{58}$.

How are samples selected when batching?


Custom view mode for entity references - getting rid of title

Question: I have an entityreference field that displays content in a custom view mode. It works great.
The only problem is that in addition to the fields that I placed in my custom view mode, it also displays the title as a link to the content. I would like to replace it and have another field (that is already in the view mode) be used as the link to the content. Also the title is appearing in the markup outside the entityreference field's view mode's wrapper, making styling a bit cumbersome.
So right now I have something like the following as field output
The title of the node

headline
My cool description that has some words in it
[and a picture]

I want essentially the same thing, but minus the title, and with the headline as the link, like so:

headline
My cool description that has some words in it
[and a picture]

How do I go about getting rid of the title and substituting the headline?
Answer: You could do this with display suite as follows:

Enable display suite and display suite extras (important)
At structure > ds > list > extras > Other, enable Page title options
At Manage Display > [view mode] > [layout], enable a DS layout for your view mode
Manage Display > [view mode] > custom page title, hide the page title

DS has a lot going on. But if you need custom display modes and need to hide the page title in some cases it works well. Plus you get a lot of other nice features.
Comment: This is hard to follow, but worth finding. See: `/admin/structure/ds/list/extras`
Answer: I had almost the same problem as you recently. Eventually I changed the node--content-type.tpl files of the referenced content type tot suit my needs.
Answer: If you don't want to use display suite, you can create a new view mode in your custom module like so:
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['VIEW_MODE_NAME'] = array(
    'label' => t('VIEW_MODE_NAME'),
    'custom settings' => TRUE,
  );
}

You can administer the new view mode in the display settings for each content type. You can also enable custom template files for the view modes of each content type by adding the following in your theme's template.php file:
function MYTHEME_preprocess_node(&$vars) {
 switch($vars['view_mode'] ){
    case 'MY_VIEW_MODE':
      $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__MY_VIEW_MODE';
      break;
    case 'teaser':
      $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__teaser';
      break;
  }
}

This enables you to create template files with filenames like node--CONTENT_TYPE--MY_VIEW_MODE.tpl.php.


Differentiating $f(x)= \sqrt[x]{x}$ from first principles

Question: An interesting fact is that the point of maximum of $y=\sqrt[x]{x}$ is attained when x equals to exactly e (as seen from the pic)
I know how to differentiate $y= \sqrt[x]{x}$, by logarithmic methodology, but can anyone teach me how to differentiate this function using only the first principle?
Note: I am still a beginner, thus it would help greatly if you can include all the steps.
Comment: What do you mean by "using only the first principle"? If you mean by using the definition, I think you're in for a rather rough ride.
Comment: In addition to the answers given so far you should also verify that it is indeed a local maximum point, e.g. by showing $f''(e) < 0$ or that $f'$ changes signs at $e$.
Comment: What's the purpose of going through a very complicated manipulation that's essentially nothing else than "reproving" the chain rule and the product rule in a special case? I'll reveal you a secret: knowing how to differentiate gives you knowledge of a very wide range of limits! Many basic exercises on limits are just "adorned" derivatives.
Answer: A nice trick is to rewrite $y=\sqrt[x]x$ as $$y=e^{\frac{\ln(x)}{x}}\tag{1}$$
This is because $$y=\sqrt[x]x=x^\frac{1}{x}=e^{\ln\left(x^\frac{1}{x}\right)}=e^\frac{\ln(x)}{x}$$
Differentiating $(1)$, and setting it equal to $0$ yields: $$\frac{dy}{dx}=e^{\frac{\ln(x)}{x}}\left(\frac{1}{x^2}-\frac{\ln(x)}{x^2}\right)=0\\\Rightarrow \frac{1}{x^2}-\frac{\ln(x)}{x^2}=0\\\Rightarrow \ln(x)=1\\\Rightarrow x=e$$
Answer: I'd consider the case $x>0$. Since the functions $\exp:{\Bbb R}\rightarrow {\Bbb R}_{>0}: x\mapsto e^x$ and $\ln:{\Bbb R}_{>0}\rightarrow {\Bbb R}: x\mapsto \ln(x)$ are inverse to each other, we have $\sqrt[x]x = x^{1/x} = e^{\ln(x^{1/x})}$. From here you should be able to differentiate w.r.t. $x$.
Answer: You have the "outer" function $$\Psi(u,v):=u^v\qquad(u\in{\mathbb R}_{>0}, \ v\in{\mathbb R})$$ of two variables, with partial derivatives
$$\Psi_u(u,v)=v\,u^{v-1}\>,\qquad\Psi_v(u,v)=\log (u)\ u^v\ .$$
The function $$f(x):=\Psi\left(x,{1\over x}\right)$$ then has to be differentiated using the chain rule:
$$\eqalign{f'(x)&=\Psi_u(x,1/x)\cdot 1+\Psi_v(x,1/x)\cdot\left(-{1\over x^2}\right)\cr  &={1\over x}x^{1/x-1}+\log (x)\>x^{1/x}\left(-{1\over x^2}\right)\cr   &={\root  x \of x\over x^2}\bigl(1-\log (x)\bigr)\ .\cr}$$


What is mumbles average monthly bandwidth usage?

Question: I am wondering how much bandwidth does a Mumble server use in the span on a month. I have a dedicated Linux server with 10,000GB bandwidth/month.
In their FAQ they have this formula and information.

Worst case scenario: Number of users × Number of talking users × 133,6 kbit/s. With less aggressive quality settings, it's ~60 kbit/s, and the bare minimum is 17.4kbit/s. Note that Mumble is geared towards social gaming; its quality enables people to talk naturally to each other instead of just barking short commands, so the amount of "users talking at the same time" can be somewhat higher than expected.
  This means that a server with 20 players and 2 players talking at once requires 1-3 Mbit/s, depending on quality settings. In the server's .ini file, you can specify the maximum allowed bitrate for users as well as the maximum number of clients to allow.

But I am not sure how to calculate the monthly based on that formula. Say I use there example on the high end and use 3Mbit/s and basing it on 100Mbps = 12MB/s that would mean that I use 1.296GB/hour which means about 31.1GB/day. So monthly it would use 933.12GB.
That may be right, not 100% sure on my calculations, but it doesn't seem like 1 server should be using that much bandwidth (granted that requires 20 people in there with 2 people talking at all times).
Does this seem right? or am I missing something? Can anyone with some experience doing this kind of thing give me some insight.
Thank you
Comment: The numbers seem right.  Keep in mind that it seems very unlikely that you would have a continuous load during the entire day.  So if your server is for a group of people from the US only, you probably will only see activity during a 8-12 hour window, and the rest of the day the server will be idle.
Comment: I don't understand your "3Mbps and basing it on 100Mbps" comments. How many users and talking users do you expect? How many hours per day are your users online?
Comment: @Alex Holst its not "3Mbps and basing it on 100Mbps" its "basing it on 100Mbps = 12MB/s" and I was just looking for an average, I'm trying to figure out how many murmur servers I can have up per linux server if each server has 10,000GB bandwidth available to it.
Comment: @Zoredache that is true, so it would realistically be about half of that provided that it would be a continuous load for the active hours. I'm assuming that it takes little to no bandwidth when there is no one talking, but I am not sure of that.
Answer: Those numbers seem sane, if (as people have commented) your numbers of users/talkers are relatively constant throughout the day -- or at least, average out at the figures you've started from. http://goo.gl/fdp3P certainly gives a similar final answer, just under 1 TB per month.
I think the useful way to look at it is actually in reverse: in a month, you can use 10TB of transfer before risking overage charges or bandwidth throttling. 10TB per month is around 32Mbps -- so how many users/talkers would you need to average at to reach this? At maximum quality, this allows you something like 4 talkers and 60 users (32Mbps/133.6kbps ~= 240) averaged through the month before you max out your bandwidth -- assuming you don't need the allowance for anything else, of course! Obviously if you're already using half your transfer allowance for something else, you need to halve this...
Sounds to me like you've got plenty of bandwidth available for the task, even if the (worst case) estimates of what you'll use are a little alarming at first.


Series of data, how to determine if I have an abnormal spike?

Question: I have a some simple chronological data as shown below. I'm new to stats but I have a math background. If I'm writing a Python script, how would I detect when I see a jump in value, eg starting around 2020-11-29 21:00:00:
<code>2020-11-28 11:00:00     6
2020-11-28 12:00:00     4
2020-11-28 13:00:00    11
2020-11-28 14:00:00     8
2020-11-28 15:00:00     8
2020-11-28 16:00:00     3
2020-11-28 17:00:00     7
2020-11-28 18:00:00     2
2020-11-28 19:00:00     2
2020-11-28 20:00:00     6
2020-11-28 21:00:00     2
2020-11-28 22:00:00     9
2020-11-28 23:00:00    22
2020-11-29 00:00:00     5
2020-11-29 01:00:00     5
2020-11-29 02:00:00    15
2020-11-29 03:00:00     5
2020-11-29 04:00:00     8
2020-11-29 05:00:00    14
2020-11-29 06:00:00     5
2020-11-29 07:00:00    12
2020-11-29 08:00:00     7
2020-11-29 09:00:00     9
2020-11-29 10:00:00     2
2020-11-29 11:00:00     6
2020-11-29 12:00:00     7
2020-11-29 13:00:00     9
2020-11-29 14:00:00     8
2020-11-29 15:00:00     8
2020-11-29 16:00:00    11
2020-11-29 17:00:00     6
2020-11-29 18:00:00     2
2020-11-29 19:00:00     5
2020-11-29 20:00:00     5
2020-11-29 21:00:00    10
2020-11-29 22:00:00    15
2020-11-29 23:00:00    12
2020-11-30 00:00:00    12
2020-11-30 01:00:00    12
2020-11-30 02:00:00    17
2020-11-30 03:00:00    20
2020-11-30 04:00:00    21
2020-11-30 05:00:00     5
2020-11-30 06:00:00    26
2020-11-30 07:00:00    19
2020-11-30 08:00:00    20
2020-11-30 09:00:00    21
2020-11-30 10:00:00    25
2020-11-30 11:00:00    12
2020-11-30 12:00:00    18
2020-11-30 13:00:00    13
2020-11-30 14:00:00    19
2020-11-30 15:00:00    30
2020-11-30 16:00:00    21
2020-11-30 17:00:00    19
2020-11-30 18:00:00    22
2020-11-30 19:00:00    20
2020-11-30 20:00:00    33
2020-11-30 21:00:00    29
2020-11-30 22:00:00    29
2020-11-30 23:00:00    27
2020-12-01 00:00:00    30
2020-12-01 01:00:00    35
2020-12-01 02:00:00    35
2020-12-01 03:00:00    22
2020-12-01 04:00:00    25
2020-12-01 05:00:00    20
2020-12-01 06:00:00    16
2020-12-01 07:00:00    34
2020-12-01 08:00:00    29
2020-12-01 09:00:00    41
2020-12-01 10:00:00    24
2020-12-01 11:00:00    31
2020-12-01 12:00:00    31
2020-12-01 13:00:00    27
2020-12-01 14:00:00    32
2020-12-01 15:00:00    34
2020-12-01 16:00:00    26
2020-12-01 17:00:00    26
2020-12-01 18:00:00    32
2020-12-01 19:00:00    25
2020-12-01 20:00:00    28
2020-12-01 21:00:00    37
2020-12-01 22:00:00    27
2020-12-01 23:00:00    31
2020-12-02 00:00:00    24
2020-12-02 01:00:00    28
2020-12-02 02:00:00    28
2020-12-02 03:00:00    22
2020-12-02 04:00:00    15
2020-12-02 05:00:00    25
2020-12-02 06:00:00    16
2020-12-02 07:00:00    10
2020-12-02 08:00:00    19
2020-12-02 09:00:00    17
2020-12-02 10:00:00    26
2020-12-02 11:00:00    29
2020-12-02 12:00:00    23
2020-12-02 13:00:00    31
2020-12-02 14:00:00    29
2020-12-02 15:00:00    42
2020-12-02 16:00:00    36
2020-12-02 17:00:00    26
2020-12-02 18:00:00    27
2020-12-02 19:00:00    24
2020-12-02 20:00:00    28
2020-12-02 21:00:00    12
2020-12-02 22:00:00    14
2020-12-02 23:00:00    30
2020-12-03 00:00:00    19
2020-12-03 01:00:00    19
2020-12-03 02:00:00    45
2020-12-03 03:00:00    35
2020-12-03 04:00:00    28
2020-12-03 05:00:00    13
2020-12-03 06:00:00    23
2020-12-03 07:00:00    13
2020-12-03 08:00:00    16
2020-12-03 09:00:00    26
2020-12-03 10:00:00    20
2020-12-03 11:00:00    19
2020-12-03 12:00:00    33
2020-12-03 13:00:00    21
2020-12-03 14:00:00    38
2020-12-03 15:00:00    43
2020-12-03 16:00:00    40
2020-12-03 17:00:00    29
2020-12-03 18:00:00    28
2020-12-03 19:00:00    43
2020-12-03 20:00:00    36
2020-12-03 21:00:00    47
2020-12-03 22:00:00    19
2020-12-03 23:00:00    17
2020-12-04 00:00:00    24
2020-12-04 01:00:00    28
2020-12-04 02:00:00    22
2020-12-04 03:00:00    13
2020-12-04 04:00:00    26
2020-12-04 05:00:00    29
2020-12-04 06:00:00    28
2020-12-04 07:00:00    28
2020-12-04 08:00:00    16
2020-12-04 09:00:00    21
2020-12-04 10:00:00    26
2020-12-04 11:00:00    29
</code>
Comment: Research the threads with the [tag:change-point] tag.
Comment: I would start off by plotting it first and then start looking into some statistical tests possibly
Comment: @Stochastic can you recommend some statistical tests that I can research that might work here?
Comment: I think it depends what your objective is. If you want to fit a time series model like an ARIMA model for example it might be feasible to fit an intervention where you see the "jump".
Answer: There is a good introductory tutorial for Python here.  This includes statistical tests mainly for Normal distributed data.  I won't repeat the whole tutorial here but the authors suggest 3 ways of performing a changepoint analysis in Python.
If you want more advanced techniques then you may be better looking at rPy2 as I don't believe the functionality is currently available in Python (although plans are in the pipeline!).


Concerning an identity related to the arithmetic mean

Question:
Let $x_1,x_2,\ldots,x_n$ be real numbers. Show that for all $c \in \mathbb{R}$ holds
$$\sum_{i=1}^n(x_i-c)^2 = \sum_{i=1}^n(x_i-\bar{x})^2+n(\bar{x}-c)^2.$$

I tried to expand the terms on both sides and obtained:
$$\sum_{i=1}^n(x_i-c)^2 = \bigg(\sum_{i=1}^n x_i^2 -2x_ic \bigg)+ nc^2$$
$$\sum_{i=1}^n(x_i-\bar{x})^2 = \sum_{i=1}^n \bigg(x_i^2-2x_i\bar{x}\bigg) +n\bar{x}^2$$
$$n(\bar{x}-c)^2 =  n\bar{x}^2-2n\bar{x}c+nc^2$$
So all that is left is to show that:
$$\bigg(\sum_{i=1}^n x_i^2 -2x_ic \bigg) = \sum_{i=1}^n \bigg(x_i^2-2x_i\bar{x}\bigg)+2n\bar{x}^2-2n\bar{x}c $$
, which I just do not manage. Could you help me?
Comment: One of your $x_i$ should be $x_i^2$
Comment: is there something special about the mean of the set? or should the relation hold when we replace $\overline{x}$ with any real number?
Comment: I am trying to hint that you have yet to use the definition of the mean, maybe this would help? @3nondatur
Comment: Thanks for pointing this out, I corrected it.
Comment: @RyanK: No, the set of $x_i$'s is not special in any way, and $\bar{x}$ is the mean value.
Answer: You can prove the result without direct algebraic computations using the notion of expected value.
In this answer, I'll denote the mean using $\mu$ instead of $\bar x$, the former being the usual notation in probability theory.
Dividing both sides of the result you need to prove by $n$, note that the problem is to prove $$\Bbb E[(X-c)^2]=\Bbb E[(X-\mu)^2]+(\mu-c)^2$$
where the probability distribution is the discrete uniform distribution on $\{x_i\}$ and $\Bbb E$ denotes expected value. Also, note that $\Bbb E[X]=\mu$ by definition.
By linearity of expected value, note that,
$$\begin{align}\Bbb E[(X-c)^2]-\Bbb E[(X-\mu)^2]&=\Bbb E[(X-c)^2-(X-\mu)^2]\\&=\Bbb E[(\mu-c)(2X-\mu-c)]\\&=(\mu-c)(2\Bbb E[X]-\mu-c)\\&=(\mu-c)(2\mu-\mu-c)=(\mu-c)^2\end{align}$$
which is what we wanted to prove. $_\square$

A more general result: $$\Bbb E[(X-a)^2]-\Bbb E[(X-b)^2]=(b-a)(2\mu-a-b)$$
for scalars $a,b$
Written another way,
$$\sum_{i=1}^n (x_i-a)^2=\sum_{i=1}^n (x_i-b)^2 + n(b-a)(2\bar x-a-b)$$
Your problem is the special case $a=c\in\Bbb R$ and $b=\bar x$
Answer: In your last equation you still have an $x_i$ that should be replaced with $x_i^2$, and a $\bar{x}$ that should be $\bar{x}^2$.

$\sum_i x_i^2$ can be canceled from both sides.
The $-2x_ic$ on the left-hand side equals $-2n\bar{x} c$.
On the right-hand side show that $\sum_i (-2x_i \bar{x})$ equals $2n\bar{x}^2$.


What parts of a Roaming Profile get uploaded in Windows 7?

Question: In previous versions of Windows, the Roaming Profile is uploaded only when the user logs off.  However, in Windows 7, a Group Policy setting can allow the registry file to be uploaded in the background.  The setting is called Background upload of roaming user profile's registry file while user is logged on.
However, with this setting set,  the Win32_UserProfile LastUploadTime field in WMI still only reflects the last log off.  I assume that this is because more than just the registry file need to be uploaded to the server in order to qualify as a full upload.
So, my question is: What other parts of the profile are uploaded on log off?
Answer: Everything in the local user profile folder (pointed to by the environment variable %USERPROFILE%) gets synchronized with the roaming profile on the file server at logoff, except folders configured in the exclusion list.
On Windows 7 the exclusion list contains by default:

$Recycle.bin
AppData\Local
AppData\LocalLow

On Windows 10 1511 the exclusion list contains by default:

$Recycle.bin
AppData\Local
AppData\LocalLow
OneDrive
Work Folders

The list is stored in the registry, at
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ExcludeProfileDirs
It can be configured via the Group Policy setting
User Configuration\Administrative Templates\System\User Profiles\Exclude directories in roaming profile.
For more information please see my article How to Reduce the Size of Roaming Profiles and Microsoft Knowledge base articles KB315415 and KB814592.
Comment: @helge fantastic answer! Thanks in particular for linking to your article. This lead to your Profile Toolkit suite of information about Windows profiles, which is just so, so useful to have in one place. So, thanks!
Comment: Note that on Windows 7 (32-bit) changing the policy causes `ntuser.ini` to be updated on the next login, but DOES NOT update the value at `HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ExcludeProfileDirs`
Answer: Lots of things - it sounds like your understanding of Roaming Profiles is fairly lacking. The user registry (Which is really NTUSER.DAT) is only one half of the story. I'd suggest browsing to your roaming profiles location (The one on the server, rather than the workstation) and you'll all of the other stuff such as Application Data and maybe the Desktop etc etc.
All of the things you see there are uploaded at log off, and downloaded at log on.
Comment: No that's not quite correct, things are syncronized at logon, not uploaded.  background uploads allow you to set time intervals or specific times to do uploads.  So at log off it's entirely possible that very little (if anything ) is uploaded
Comment: You're right @JimB that's a good point. Though I interpreted as the OP not realising there was more to a roaming profile. Additionally, background uploads need to be specifically configured so we can probably assume they don't use them.
Comment: even without background uploads enabled, only changes would be synchonized so what gets uploaded depends always on usage.


Beginning Counterpoint

Question: Can I start a 5th species counterpoint on a perfect 12th instead of a perfect 5th when the cantus firmus is in the lower voice?
Comment: The example does not make clear what the lower voice is doing.  From the A5 to the second C5 there is only one voice.  Does the lower voice rest?  Does it sustain the F?  Are the notes from beat 2 to 4 of the second measure for the lower voice?  If so what does the upper voice do?  Starting with a 12th is among the least of the problems here.  If the two voices were shown distinctly, it would be possible to decide whether simply lowering the upper voice by an octave would solve the problem of the 12th or whether another solution might be possible.
Answer: In strict terms, no. One of basic rules underlying all of the species is to keep both voices within an octave of each other, although tenths are permissible.
However, for the purposes of one's own learning, it's fine, because the concepts being reinforced in fifth species still apply. The thing on which one misses out is the compositional challenge of limiting the range of the voices, which is valuable in itself as preparation for composition beyond exercises.
Comment: @JDWashington Your points are well taken, but also demonstrate your own limited understanding. Fux was not writing within the context of tonality, nor does he consider the modulations you have in mind. His model was Palestrina, who wrote modally and who is not known to have written instrumental music. Palestrina-style, sacred vocal music was the central motivation for Fux.
Comment: P.S. It's been some time since I last studied Fux, but I don't recall seeing intervals greater than a 10th between adjacent voices, which is what I interpreted your question to address, since the example comprises two voices.
Comment: The perfect 12th is actually allowable "within" the counterpoint, and Fux uses it as well as the P11th in many situations; it's the Major13th that exceeds the threshold of strict counterpoint in 2voices. Your understanding of the Contrapunctus seems limited. Starting on the perfect 12th would allow me to modulate from Cmajor to Fmajor without leaping by a fourth to arrive at the subsequent tonic(which is stylistically attractive to me because leaps less than a third do not require compensation).
Comment: *In my opinion, the ranges of strict counterpoint should not be further limited because the compound intervals give more variety in the permutations of harmonies(would you really want to just hear 3rds, 5ths, and 8ves in your "perfect world" of instinctively limiting the ranges?....answer is no. You should be lucky that you can hear a Ma10,Mi10, Ma3, Mi3, P5th and P12 because that allows muchhhh more HARMONY.) The independence lost by preferring a P5 to a P12th should be of no consequence, because the rules determined its stability.
Comment: *P.S. I would never actually start on a P12 but I was just curious ,as a pianist and theorist, why the compound version of the unison(obviously the 8ve) can begin the counterpoint but the compound version of the 5th does not, especially if the 12th won't be exceeded anyways...if we're talking about independence of lines, then wider intervals should be preferred to discourage voice crossing which is the real problem that Fux could not even avoid.
Comment: @JDWashington you can totally start on a 12th if there are multiple voices.  The thing with this style of counterpoint, though, is that you lose the sense of blending of the voices if two adjacent voices are separated by so much.  A piece for soprano instrument (flute, violin, etc.) or voice with basso continuo accompaniment will routinely include larger intervals, but that is far enough outside the scope of "species counterpoint" that the interval-size rule is relaxed (and the continuo realisation fills the gap, anyway).

Beginning Counterpoint


Print a specific column from a tab-delimited file in python

Question: I am a beginner with python. I have a  tab-delimited file and I want to print only the 37th column which is the last column. But when I run this code the whole data is printed. my code goes as follows:
dicts = {}
for i in open('Book2.txt'):
    split_i = i.split('\t')
    dicts[split_i[37]] = i.rstrip()
    print(i.rstrip())

Answer: In line 4, rstrip() is a string function to remove trailing whitespace, not to grab the last word. Since split() created a list from the string in the previous line, you can use list indexing, like split_i[-1] to index the rightmost item of the list, or split_i[36] to get the 37th from the left.
Additionally, this may not be the right use of a dict. Try creating a list instead, such as:
col_37 = []                        # Empty list instead of a dict
for line in open('Book2.txt'):     # Variable 'i' named more intuitively
    split_line = line.split('\t')  # Separate the string by tabs
    col_37.append(split_line[36])  # Add the item you want to your list
print(col_37)                      # Show the data you just got

Comment: `split_i[37]` is not the 37th from the left.
Answer: Lists in python are zero indexed. which means the first element has an index of 0. So for the 37th column it would be mylist[36]. Since you want the last column there is a shortcut mylist[-1] which always returns the last element of the list.
for line in open('Book2.txt'):
    print(line.split('\t')[-1])

List comprehension is a much cleaner and more pythonic approach to handle a simple for loop:
lines = open('Boot2.txt')
col = [line.split('\t')[-1].rstrip() for line in lines]
print("\n".join(col))


How to prove Linear Independence in the below question?

Question: I am solving Linear Algebra and stuck in middle of the problem.
''Let V be the set of all real valued functions y = f(x) satisfying y''+4y=0. Prove that V is a 2-dimensional real vector space.''
I know Basis of the above set is {cos 2x, sin 2x}.How to prove Linear Independence in this set ?
Any help is appreciated.
Comment: Consider the [Wronskian](https://en.m.wikipedia.org/wiki/Wronskian)
Answer: Suppose $\sin$ and $\cos$ are linearly dependent, that is, there exist constants $a, b$ such that $a \sin(x) + b \cos(x) = 0$ for all $x$. Setting $x = 0$, we get $0 = a \sin(0) + b \cos(0) = a \cdot 0 + b \cdot 1 = b$, hence $b = 0$. But then $a \sin (x) = 0$ for all $x$, which is only true if $a = 0$.
Comment: you could set $x =\pi/2$ to show $a = 0$, since $a \sin(\pi/2) + b \cos(\pi/2) =0 \Rightarrow a = 0$
Comment: I was hoping somebody would explain using Wronksian and then i would ask about it.


Estou com problema em um site que fiz usando vuejs, erro 404 NoSuchKey

Question: Desenvolvi um site em vuejs utilizei vue-router para os caminhos, porem quando acesso a pagina ela carrega normal, porem quando estou em um /services e recarrego a pagina da o erro
<Error>
NoSuchKey
<Message>The specified key does not exist.</Message>
<Key>services</Key>
<RequestId>000000000</RequestId>
<HostId>sadsasadsadasdasdassaasddas=</HostId>
</Error>

antes estava dando erro 403 forbien, agora 404 me ajudem ai, se quiser ver o repositorio esta no github meu
https://github.com/danielurba/site-personal-car-vuejs
site que esta dando problema
https://www.personalcarcvel.com.br
Answer: Este pode ser um problema da configuração de seu vue-router ou no servidor.
Verifique as configurações de sua rota se elas possuem uma tratativa para acessos diretos ou atualizações, que são novas requisições ao servidor.
Ambos os casos são explicados aqui:
History Mode vue-router
Pode tentar adicionar em sua criação do routes o seguinte:
const router = new VueRouter({
    mode: 'hash',
    routes
})

Se estiver usando Apache tente adicionar o seguinte ao seu .htaccess:
<ifModule mod_rewrite.c>
    RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</ifModule>


Impedir indexamento de recortes da pagina

Question: Se recortar uma pagina separando o head,nav, etc... E puxar tudo com include no index.php, o Google vai indexar essas paginas recortadas?
Quero separar algumas partes criando head.php e nav.php, depois vou puxar para dentro do index fazendo um include, mas preciso que o google faça a indexação da minha index MAS não faça a indexação dos arquivos head.php e nav.php pois esses serão apenas recortes para facilitar na manutenção, isso é possivel?
Visto que se eu der um no index no arquivo head.php os robos de buscas não só vão parar de indexar o head.php mas também vão parar de indexar minha index inteira pois estarei puxando o arquivo nela, como proceder?
Answer: O google "vê" e processa apenas o que o teu servidor manda como resposta, de maneira simples se clicares com o botão direito do rato e clicares em ver fonte (view page source para browsers em inglês) é isso que o google processa, apesar de conseguir ir um pouco mais longe e identificar/processar manipulações do DOM com javascript com recurso por exemplo a ferramentas como Selenium.
De qualquer maneira o google e outros motores de busca não conseguem identificar os processos internos do servidor, apenas o que este manda para o lado cliente e os processos que ocorrem neste lado (no browser).
Ex:
head.php
<!DOCTYPE html>

        <title>SO PT</title>

index.php
<?php include('head.php'); ?>

Olá SO PT

Os web crawlews da google daqui (index.php) vão processar/ver apenas:
<!DOCTYPE html>

        <title>SO PT</title>

Olá SO PT

Não vai saber se o head.php foi "injetado" no index.php via um include/require.
Desta maneira e para responder diretamente à tua pergunta, desta maneira não tens como incumbir os robots de ver somente uma parte da página.
Comment: mas o google faz uma busca no servidor por arquivos, nesse caso ele consegue fazer a captura de todos arquivos publicos no servidor, ate mesmo um scanner como Vega consegue fazer a captura desses arquivos, ou estou errado? tanto que ate arquivos de texto da qual o site não faz nenhum chamada o google e alguns scanners conseguem encontrar de boa, é por isso que acredito que eles também irão encontrar os arquivos recortados como o head.php e nav.php por exemplo
Comment: @OtavioFagundes, esses softwares vão indo por tentativas e vendo se o servidor responde de alguma maneira de forma a verem se estes existem. Por exemplo, http://migueldvl.com/nao_ver_conteudos , aqui é preciso ir por tentativas e ir experimentanto se algum url responde alguma coisa, se experimentassem http://migueldvl.com/nao_ver_conteudos/ola.php , já encontrariam esse ficheiro, MAS nunca (partindo do príncipio que está tudo bem em termos de segurança) conseguirá ver o conteudo do ficheiro entre as tags `;`.
Comment: Isso seria um erro tremendo, porque teria acesso a informação sensível. Por ex: configuração da base de dados, do pŕoprio servidor etc... De qualquer maneira não acho e tenho 99% de certeza que o google não se baseia nisto para indexação do teu site, mesmo que de alguma maneira consiga ver que tens o head.php separado do index.php, isso não deve influenciar em nada


Renderizar legendas no vídeo com ffmpeg?

Question: Tenho alguns arquivos de legenda que estão separados de seus respectivos vídeos, e eu gostaria de junta-los, usando o código abaixo:
ffmpeg -i videoSemLegenda.mp4 -i legenda.vtt -c copy -c:s mov_text videoComLegenda.mp4

Ao obter a saída no videoComLegenda usando ffmpeg -i videoComLegenda.mp4
A saída do ffmpeg mostra que a legenda está junto com o vídeo, porém ao tentar reproduzir o vídeo na tag <video> a legenda não é mostrada. Como faço para forçar a legenda a ser escrita dentro do vídeo?
Essa é a saída ffmpeg para um arquivo cuja as legendas foram colocar através do código acima:
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x960 [SAR 1:1 DAR 4:3], 1459 kb/s, 29.97 fps, 29.97 tbr, 16k tbn, 59.94 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(por): Audio: mp3 (mp4a / 0x6134706D), 48000 Hz, stereo, s16p, 256 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
    Stream #0:2(und): Subtitle: mov_text (tx3g / 0x67337874) (default)
    Metadata:
      handler_name    : SubtitleHandler

Comment: @LeoLetto Cara, você já tentou incluir a legenda como arquivo externo mesmo utilizando o , como na referência do elemento?
http://www.w3schools.com/TAgs/att_track_kind.asp
Comment: @LeoLetto Então só re-encodando o vídeo e de fato renderizar o texto junto a imagem. Tive que fazer isso há uns 3 anos e com mídias protegidas por DRM, fui o único jeito.
Comment: da uma lida nas respostas dessa pergunta no SO: [Use ffmpeg to add text subtitles](http://stackoverflow.com/questions/8672809/use-ffmpeg-to-add-text-subtitles)
Comment: Os comandos lá passados funcionam da mesma maneira, colocam o arquivo de legenda dentro do recipiente mas os mesmos não aparecem no player
Comment: Eu não posso votar pra fechar na sua pergunta porque ela está com uma recompensa ativa. Mas eu acho que ela não faz parte do escopo do site porque não é sobre programação (e sim sobre o uso de um software).
Comment: Fiquei com uma dúvida, você quer "embeddar" a legenda para que ela seja renderizada junto ao vídeo, adicionar como track dentro do container ou simplesmente reproduzir um video com legenda usando o player nativo do elemento  ?
Comment: Mas @LuizVieira apesar da pergunta fazer referência a um software, a dúvida se aplica renderização de uma legenda dentro do vídeo para ser exibida dentro de uma tag , logo não acredito que ela fuja do escopo do site, e no SO existem várias perguntas referentes ao mesmo software, logo não acredito que haja algum problema.
Comment: @LeandroAngelo quero que a legenda seja renderizada junto vídeo quando o mesmo for reproduzido em um player HTML
Comment: @LeoLetto Sim, ela se aplica à renderização da legenda dentro do vídeo. Ou, em outras palavras, a um uso do ffmpeg que não tem relação alguma com programação. Talvez existam perguntas referentes ao uso do mesmo software *em um contexto de programação* (como automatizar, como integrar, etc). Se não, eu também votaria para fechá-las.
Comment: Por ser um software Command-line acho que isso o inclui um pouco na categoria de programação.
Comment: @LeoLetto Se por acaso a sua intenção é fazer isso de forma automatizada dentro de um site (em PHP, talvez?) para o vídeo ser apresentado corretamente para o cliente HTML, deixe isso claro na questão. Aí sim eu acho que ela faria parte do escopo do site. :)
Comment: Discordo. Caso contrário, qualquer software se incluiria na categoria programação.
Comment: Sim sim @LeandroAngelo chamando a mesma através de um arquivo externo funciona perfeitamente, mas por motivos de curiosidade eu queria saber se é possível apenas embuti-la no vídeo
Comment: Olha só, Leo, como dá pra facilmente tornar a sua pergunta dentro do escopo, com base no que o colega @LeandroAngelo menciona. Acho que é só uma questão de vc editar a pergunta e melhorá-la incluindo essas informações do que você já tentou (e pode até mesmo mencionar que a sua busca por embutir trata-se de curiosidade - apesar de que a questão da proteção por DRM é bem relevante). Se editar nesse sentido, aliás, ganha o meu +1. :)
Comment: Eu não tenho intuito de fazer isso para proteger os arquivos, não vejo necessidade de editar a pergunta mudando o sentido da mesma, ta simples e objetiva de forma que também espero uma resposta simples, e não vejo por que o fator de ser uma pergunta só por "curiosidade" deveria influenciar na resposta. Enfim não vou discutir sobre até por que é proibido transformar comentários em chat. Peço desculpas a quem não gostou do escopo abordado na pergunta.
Answer: Como você mesmo pôde ver nas informações do vídeo a legenda está codificada na segunda trilha de dados, inclusive, esta pode ser reproduzida normalmente pelos players que a suportem, mesmo que, talvez, seja necessário habilitar manualmente.
Você tem como alternativas utilizar a marcação <track> da tag  <video> desde que atente para as particularidades, limitações e possíveis problemas de cada navegador. Exemplo:

Algumas versões do Internet Explorer não vai reconhecer legendas no formato VTT definidas por essa marcação a não ser que você defina o Content-type pelo servidor (.htaccess e similares)
Chrome e Opera ignoram o atributo default e tentam combinar o idioma do browser com a legenda, provavelmente levando em conta o valor de srclang.
Comigo isso não funcionou. O ícone 'CC' sequer apareceu

Então, pelo sim pelo não, se o seu público alvo vai rumo à um único idioma, convém você embutir as legendas no vídeo:
ffmpeg -i "path/to/video.mp4" -vf srt="subtitle.srt" "path/to/video-subtitled.mp4"

Ou, se quiser estilizar a legenda, com o formato ASS (Advanced SubStation Alpha):
ffmpeg -i "path/to/video.mp4" -vf ass="subtitle.ass" "path/to/video-subtitled.mp4"

Caso precise converter de um formato pra outro, a FFMPEG também faz isso pra você:
ffmpeg -i "path/to/subtitle.srt" "path/to/subtitle.ass"

Agora se seu público alvo exigir múltiplas legendas, em múltiplos idiomas (e o Youtube não for uma opção ^_^), você vai mesmo ter que usar alguma biblioteca em JavaScript que dê conta do maior número de particularidades possível, nem que elas tenham que criar toda a UI do vídeo manualmente, como no artigo do MDN
Answer: O HTML5 puro não dá suporte para legendas embutidas nos arquivos. O que você pode fazer é separar os arquivos e chamá-los como está abaixo:
<video controls preload="metadata">
   <source src="path/to/videos/my_video_1.mp4" type="video/mp4">
   <track label="Português" kind="subtitles" srclang="pt" src="path/to/captions/my_video_1.vtt" default>
</video>

Porém, existe um plugin, mp4Box, que consegue pegar essas legendas embutidas. Neste link, ele fala como extrair essas legendas.


Using Synthesis to Create Original Sounds

Question: Many videos I've watched on synthesis aim at emulating physical instrument sounds (or sometimes physical sound effects), with the pursuit of realism as a guiding principle.  At first, this struck me as something in the neighborhood of a skeuomorph.  I wondered why the contingent attributes of physical objects should dictate sound design principles now that their limitations can be put aside using synthesizers, whose space of possible sound outputs is much larger (at least if we ignore differences between indiscernibly similar sounds).
Later I discovered the answer that our ears have evolved to appreciate the sounds physical instruments and objects can produce, because they have been with us for so long, but I still wonder how musically useful synthesis can be for producing original sounds rather than emulation.

Very qualitatively, what percentage of possible sounds a synthesizer can output are viable for music?  I know an exact numerical percentage would depend on way too many factors and boundaries, but I just want a general sense of how sparsely musically-viable sounds occupy the space of all producable sounds.

Again very qualitatively, what percentage of those musically-viable sounds correspond to sounds produced by physical instruments or objects?  Is that evolutionary correlation between the ear and the physical so strong that it accounts for nearly all of our ability to find pleasure in musically viable sounds, or does synthesis unlock a large amount of musical potential not grounded in emulation of the physical?

If synthesis does open these original avenues, is there a field of study which teaches how to create music by designing these original sounds, rather than by emulating physical instruments or objects?
Comment: Have you ever played with a synthesiser :)?
Comment: "Many videos I've watched on synthesis aim at emulating physical instrument sounds" — probably because emulating a physical sound is a _more specific, easier to define and measure, goal_ than "aim at making interesting sounds", and thus easier to write a useful tutorial about. That shouldn't be taken as evidence about what the possible uses of synthesizers are.
Comment: Both 1. and 2. seem a bit pointless. Since synthesizers have many parameters that affect the production of sounds (and since there are thousands of very unique synthesizers), the "possible sounds" are fundamentally *infinite*. For the same reason, there are virtually infinite combinations of sounds produced by "objects". Then, "pleasure" of sounds also depends on social culture and education: the same sound could be pleasing to some and awful to others, even if it comes from a good instrument wonderfully played.
Comment: If you listen to much music made after say 1930, in almost any genre, you're already hearing completely original sounds made by synthesizers. One ultra-famous example is the high note hook from "Nothin But A G Thang". Also the theremin part from "Good Vibrations". Regarding question 3, one excellent way to learn how to invent new sounds is to practice imitating acoustic sounds.
Answer: No.1 is easy to answer: every conceivable sound has a potential musical use, so of course that includes any possible synthesizer sound.
No.2 is unanswerable without a rigorous definition of what sounds correspond to physical instruments
No.3 is easy: the field of study is called "synthesis". The emulation of physical instruments is just a small part of the field.
Answer: This seems like a lot objective and qualitative questions surrounding a subjective core: the phrase "musically useful." For something to be musically un-useful, a host of assumptions about aesthetic context and aim come into play. (Cue a reference to Hindemith and "Music for use?") Synthesis was born and evolved through experimentation and trial-and-error, which always means pursuing some avenues without being convinced of their usefulness beforehand. As PiedPiper also notes, the distinction between sounds that emulate physical sources and those that don't is a difficult and fuzzy one, especially if we're talking not just about intent but about product. If a bass pad, created without intent to emulate, happens to be "indiscernibly similar" to a foghorn, does it count as matching a physical source?
(Here's something to muddy the philosophical waters: what happens when we use physical objects to emulate electronic sounds? https://g.co/kgs/wAw3vn)
It seems that there are two seeds to your post: Issues of intent and guiding philosophy in the pursuit of synthesis ("Why are we so hung up on emulating physical sources?"), and speculation about psychoacoustics ("Have humans evolved to respond more strongly to physical sources?"). Stripping away the subjective, my answers would be:

I don't know that the field of synthesis is still disproportionately emphasizing emulation. Can that be shown?
I think the question about human response to physical sounds rests on too tenuous of a distinction between "physical" and synthesized sounds. There is study into human response to certain frequencies, often accompanied by speculation about evolutionary explanations. But I think it would be hard to test "artificial" sounds (especially since we've been acclimating to artificially reproduced sound since the late 19th century).


How to update custom AMIs using packer and integrated with auto-scaling group?

Question: Goal: To maintain the minimum startup period for bringing up instances to load balance and reduce the troubleshooting time.
Approach:

Create base custom-AMI for ec2-instances
Update/rebundle the custom AMI on every release and s/w patches (code & software updates related to the healthy running instance).
2.a. Packer/any CI usage for update is possible? If so, how? (unable to  find a step-by-step approach in documentations of package)
Automate the step 1 and step 2 using chef.
Integrate this AMI in the Auto scaling group (experimented this).
Map the Load balancer to ASG [done].
Maintain the desired count of Instances by bringing up instances from updated-AMI in ASG with LB upon failure.

Crux: Terminate the unhealthy instance and bring up the healthy instance with ami asap.
--
P.S:
I have gone through many posts from [http://blog.kik.com/2016/03/09/using-packer-io-to-optimize-and-manage-ami-creation/] and https://alestic.com/.
Using docker is rolled out of discussion.
But still unable to figure out a clear way to do it.
Comment: Removing the Chef tag as how you build you AMIs is unrelated to ASG upgrades.
Answer: The simplest way to swap out a new AMI in an existing ASG is to update the launch config and then one by one kill any instance using the old AMI ID. The ASG will bring up new instances as needed, which should use the new AMI. If you want to get fancier (like keeping old instances alive for quick rollback) check out tools like Spinnaker which brings up each new AMI as a new corresponding ASG and then remaps the ELB to swap traffic over if no problems are detected, and then later on when you are sure the deploy is good it kills off the old ASG and all associated instances.
Comment: How about automating the ami creation using packer ?! is tat an efficient solution for quick firing up the instance upon failures ?
Comment: Those two things are unrelated. How you build an AMI is separate from you use it.
Comment: sure thanks.. got clarified ! lot more hovering..so confused ! thanks for the answer
Comment: Thank you for mentioning Spinnaker. I have been using Terraform for deploying provisioned infrastructure. Blue/green deploys may work be easier (for me) with Spinnaker.