Como espelhar uma imagem?

Question: Gostaria de sabe como faço para espelhar uma imagem.
Consegui um algoritmo, mas ele só inverte imagens com resolução 60x60 e bpp=1.
Tenho o seguinte modelo de imagem para testar:
unsigned char icon[] ={
    //HEADER
    0x42, 0x4D,             // 0-1   BM
    0xF6, 0x07, 0x00, 0x00, // 2-5   uint32 filesize (not reliable)
    0x00, 0x00, 0x00, 0x00, // 6-9   uint32 0
    0x76, 0x00, 0x00, 0x00, // 10-13 uint32 bitmapOffset

    0x28, 0x00, 0x00, 0x00, // 14-17 uint32 info size
    0x3C, 0x00, 0x00, 0x00, // 18-21 int32  width
    0x3C, 0x00, 0x00, 0x00, // 22-25 int32  height
    0x01, 0x00,             // 26-27 uint16 nplanes
    0x04, 0x00,             // 28-29 uint16 bits per pixel bpp bitCount
    0x00, 0x00, 0x00, 0x00, // 30-33 uint32 compression flag
    0x00, 0x00, 0x00, 0x00, // 34-37 uint32 image size in bytes
    0xC4, 0x0E, 0x00, 0x00, // 38-41 int32  biXPelsPerMeter
    0xC4, 0x0E, 0x00, 0x00, // 32-45 int32  biYPelsPerMeter
    0x00, 0x00, 0x00, 0x00, // 46-49 uint32 colors used
    0x00, 0x00, 0x00, 0x00, // 50-53 uint32 important color count
    //*********************************************
    //Dados da imagem:
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80,
0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF,
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF,
0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 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xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
                };

Alguém teria alguma ideia de onde eu deveria fazer um melhor ajuste neste algoritmo?
Suponhamos que temos uma imagem 10x10 pixels, com bpp=1. O tamanho da linha seria de 10 bits? Será que tenho que inverter esses bits por linha, para ter o resultado almejado? Alguém sabe como se faz isso?
Eis o algoritmo que tenho:
int getBytesPerRow(int bpp, int width)
{
    switch (bpp)
    {
    case 1: return (width >> 3) + ((width & 0x7) == 0 ? 0 : 1);
    case 4: return (width >> 1) + ((width & 0x1) == 0 ? 0 : 1);
    case 8: return width;
    case 24: return width * 3;
    default: return -1;
    }
}

void ImageMirror(uchar *bmpBytes, int width, int height, int lenght, int bpp)
{

    int32 bmpRowLength;
    int32 imgRowLength;
    int32 imgRow;

    struct ImageInfo imageInfo;

    imageInfo.width = width;
    imageInfo.height = height;
    imageInfo.bpp = bpp;

    // imRowLength is the number of bytes that represent each line
    // bmpRowLength is the length of line in pixels and should be rounded to the next 32 bits boundary
    imgRowLength = getBytesPerRow(imageInfo.bpp, imageInfo.width);
    bmpRowLength = (imgRowLength & 0xFFFC) + ((imgRowLength & 3) == 0 ? 0 : 4);

    imageInfo.imageLength = imgRowLength * imageInfo.height;

    imageInfo.imageBytes = wabaVm->Malloc(imageInfo.imageLength);

    // invert the image, so it's stored upside up
    for (imgRow = 0; imgRow < imageInfo.height; imgRow++)
    {
        // if row size is less than the number of pixels per row
        int index = imgRow * imgRowLength;
        uchar *bmpRow = &bmpBytes[(imageInfo.height - imgRow - 1) * bmpRowLength];
        uchar *imgRow = &imageInfo.imageBytes[index];
        memcpy(imgRow, bmpRow, imgRowLength);
    }
    memset(bmpBytes, 0, lenght);
    memcpy(bmpBytes, imageInfo.imageBytes, lenght);
    Free(imageInfo.imageBytes);
}

Comment: Não sei o que você entende como C puro, mas pelo menos alguma biblioteca gráfica você terá que utilizar.
Comment: C puro, sem ser C++.
C baixo nível. O que quero é para imprimir imagem em uma impressora térmica. A imagem está saindo invertida e de ponta cabeça. Preciso de um algoritmo que ajeite a imagem.
Comment: Importante [edit] postando o que tentou e deixando bem clara a dificuldade encontrada. Códigos prontos, tutoriais e dúvidas que dependam de vários conhecimentos diferentes aplicados normalmente não se encaixam bem no [escopo do site](/help/on-topic) em uma única pergunta. Se tiver dúvida em partes específicas, pode postar um [mcve] da etapa atual do problema, e resolvendo, pode abrir perguntas em separado sobre os passos seguintes, cada uma focada em um problema específico.
Comment: @Bacco Coloquei mais informações em relação minha dúvida.
Comment: Você talvez encontre um algoritmo em C++ que possa compilar para realizar a inversão. O [OpenCV](https://github.com/opencv) é uma biblioteca aberta de visão computacional e tem implementações bem eficientes para esse tipo de operação.
Answer: Considerando que sua imagem seja algo como:
/* Imagem 13x10 */
char image[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
                 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
                 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
                 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0,
                 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
                 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0,
                 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0,
                 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

Para inverte-la, você pode fazer a troca dos pixels contidos no começo da imagem com os pixels contidos no final da imagem, veja só:
void image_mirror( char * img, int width, int height )
{
     /* Pixel auxiliar */
    char aux = 0;

    /* Pixel canto superior esquerdo */
    char * a = img;

    /* Pixel canto inferior direito */
    char * b = &img[ ( height * width ) - 1 ];

    /* Troca os pixels do comeco com os pixels do final */
    for( ; a < b; a++, b-- )
    {
        aux = *a;
        *a = *b;
        *b = aux;
    }
}

Colocando tudo junto:
#include <stdio.h>

void image_show( char * img, int width, int height )
{
    int i = 0;
    int w = 0;
    int h = 0;

    for( h = 0; h < height; h++ )
    {
        for( w = 0; w < width; w++ )
            printf( "%s", img[i++] ?  "X " : "  " );
        printf( "\n" );
    }
}

void image_mirror( char * img, int width, int height )
{
    char aux = 0;
    char * a = img;
    char * b = &img[ ( height * width ) - 1 ];

    for( ; a < b; a++, b-- )
    {
        aux = *a;
        *a = *b;
        *b = aux;
    }
}

int main( int argc,char ** argv )
{
    /* Imagem 13x10 */
    char image[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                     0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,
                     0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
                     0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
                     0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0,
                     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
                     0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0,
                     0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0,
                     0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0,
                     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    printf("Imagem Original:\n");
    image_show( image, 13, 10 );

    /* Inverte imagem de ponta a cabeca */
    image_mirror( image, 13, 10 );

    printf("Imagem Invertida:\n");
    image_show( image, 13, 10 );

    return 0;
}

Saída:
Imagem Original:

    X X           X
        X       X
      X X X X X X X
    X X   X X X   X X
  X X X X X X X X X X X
  X   X X X X X X X   X
  X   X           X   X
        X X   X X

Imagem Invertida:

        X X   X X
  X   X           X   X
  X   X X X X X X X   X
  X X X X X X X X X X X
    X X   X X X   X X
      X X X X X X X
        X       X
      X           X X

Veja funcionando no Repl.it
Comment: Obrigada Lacobus.
Com 0 e 1 funciona bem, mas se eu colocar valores: 0xFF, 0x00, 0x0C..., que correspondem aos dados da imagem, não funciona muito bem, fica com sujeira na imagem. E o tamanho width x height também não funciona bem. No cabeçalho da imagem tem o tamanho, então substituo por esses valores. Tem algo faltando, preciso saber o que é.
Comment: Apenas usei o *formato* de imagem mais primitivo que eu pude imaginar para exemplificar. Qual é o formato da imagem na qual você está trabalhando ? Quantos bits ela possui por pixel ?
Comment: Varia... Depende da imagem que eu for abrir pra mandar imprimir. Peguei um exemplo pequeno, o bpp é 2, uma imagem 2x2 peguei como exemplo...
Comment: Eu tenho que pegar os dados da imagem e transformar em bmp. Até aí tudo bem. Só o problema é que sai espelhada a imagem, pois o formato bmp é invertido, por isso tenho que inverter a imagem.
Comment: @BiancaNunes: Qual é o formato da imagem de origem ? Tem como postar uma como exemplo/amostra ?
Comment: Editei minha pergunta. Coloquei lá em cima.
Comment: Engraçado é que quando imprimi na impressora, conseguiu ajustar apenas no aspecto de ficar ponta cabeça. Não fica mais assim. Entretanto, ainda fica espelhado.  Tentei fazer um algoritmo pra desinverter, mas não consegui.
Comment: Eu tive uma ajuda.., me passaram essa solução:

 int bytesPerRow = (width >> 3) + (width & 0x7 ? 1 : 0);
//essa parte não entendi o porquê de deslocar 3 bits para direita e dar um & lógico com 7.

int row;

                for (row = height - 1; row >= 0; row--)

                   memcpy(&(bitmapStream[sizeof(header) + row * bytesPerRow]), &rgb[(height - row - 1) * bytesPerRow], bytesPerRow);
//isso aqui entendi menos ainda...
Answer: "(...) como faço para espelhar uma imagem. (...) Será que tenho que inverter esses bits por linha, para ter o resultado almejado? (...)"
Se a intenção é espelhar uma imagem na horizontal com 1 bit por pixel (1bpp), a resposta à pergunta é sim. Da mesma forma que é necessário inverter a ordem byte por linha, também é necessário inverter a ordem pixel dentro de 1 byte.
O exemplo de "modelo de imagem para testar" da pergunta  é uma imagem BMP com 4 bits por pixel (4bpp), neste caso é necessário inverter, não a ordem bit, mas a ordem nibble (4 bits).
Imagens BMP 1bpp, 4bpp e 8bpp:
Para fazer espelhos na horizontal no formato pixel 1bpp (1 pixel por bit, ou seja, 8 pixeis por byte) é necessário inverter a ordem bit. Por exemplo, inverter a ordem bit de um byte (8 pixeis):
mirrored_Pixels_Per_Byte = (b & 128) >> 7 | (b & 64) >> 5 | (b & 32) >> 3 | (b & 16) >> 1 | (b & 8) << 1 | (b & 4) << 3 | (b & 2) << 5 | (b & 1) << 7;
Para fazer espelhos na horizontal no formato pixel 4bpp (1 pixel por cada 4 bits, ou seja, 2 pixeis por byte) é necessário inverter a ordem nibble (4 bits). Por exemplo, inverter a ordem nibble de um byte (2 pixeis):
mirrored_Pixels_Per_Byte = (b & 15) << 4 | (b >> 4);
Para fazer espelhos na horizontal no formato pixel 8bpp (1 pixel por cada 8 bits, ou seja, 1 pixel por byte) basta copiar.
Este é o formato mais simples, visto que um pixel é igual a um byte. Por exemplo:
mirrored_Pixel = b;
O problema é que para 1bpp (quando o valor "width" da imagem em pixeis não é um múltiplo de 8) e 4bpp (quando o valor "width" da imagem em pixeis não é um múltiplo de 2) nem tudo são pixeis dentro de um byte.
Por exemplo uma imagem 1bpp com 9 pixeis x 2 pixeis (width x height):
Como 9 bit-pixeis por linha ("width") não cabem em 2 bytes completos (16 bit), o último byte de cada linha de pixeis é composto por 1 bit-pixel + 7 bits de valor 0.
Estes 7 bits de valor 0 não são pixeis e devem ser mantidos no final de cada linha de pixeis.
Se forem movidos para o início de cada linha serão interpretados erradamente como pixeis e verá uma linha adicional (vertical) com 7 pixeis de largura do lado esquerdo da imagem.
Isto é válido para eventuais bytes de preenchimento "padding for 4 byte alignment" especificados para o formato de imagem BMP.
Por exemplo como 2 bytes (8 bit-pixeis + 1 bit-pixel + 7 bits de valor 0) não são um múltiplo de 4 bytes, "padding for 4 byte alignment", cada linha da imagem, neste caso, será composta por 2 bytes + 2 bytes adicionais de preenchimento. Os valores byte de preenchimento para "padding for 4 byte alignment" podem ser 0 ou qualquer outro e o seu valor não é importante.
Este "padding for 4 byte alignment" é obrigatório e a sua ausência, quando uma linha de pixeis não for um múltiplo de 4 bytes, gera um erro na imagem.
#include <stdio.h>

unsigned char icon[] ={ // bitmap 4bpp
// BITMAP FILE HEADER
       66, 77, //   0-1 (2 bytes uint16) "BM"
 246, 7, 0, 0, //   2-5 (4 bytes uint32) File size in bytes. Exemplo de como transfromar 4 bytes LE em um número: ( ( 246 ) << 0) | ( ( 7 ) << 8) | ( ( 0 ) << 16) | ( ( 0 ) << 24) = 2038
         0, 0, //   6-7 (2 bytes uint16) Reserved
         0, 0, //   8-9 (2 bytes uint16) Reserved
 118, 0, 0, 0, // 10-13 (4 bytes uint32) Offset where the image data (pixel array) can be found
// DIB HEADER
  40, 0, 0, 0, // 14-17 (4 bytes uint32) Size of DIB header in bytes
  60, 0, 0, 0, // 18-21 (4 bytes  int32) Image Width in pixels
  60, 0, 0, 0, // 22-25 (4 bytes  int32) Image Height in pixels
         1, 0, // 26-27 (2 bytes uint16) Number of color planes (must be 1)
         4, 0, // 28-29 (2 bytes uint16) Number of bits per pixel (bpp) (must be 1, 2, 4, 8, 16, 24 or 32). Exemplo de como transfromar 2 bytes LE em um número: ( ( 4 ) << 0) | ( ( 0 ) << 8) = 4
   0, 0, 0, 0, // 30-33 (4 bytes uint32) Value of compression method (can be 0, 1, 2, 3, 4, 5 or 6) (0 == compression none BI_RGB)
   0, 0, 0, 0, // 34-37 (4 bytes uint32) Size of image data (pixel array); a dummy 0 can be given for BI_RGB bitmaps
196, 14, 0, 0, // 38-41 (4 bytes uint32) Horizontal resolution of the image (pixels per meter)
196, 14, 0, 0, // 42-45 (4 bytes uint32) Vertical resolution of the image (pixels per meter)
  16, 0, 0, 0, // 46-49 (4 bytes uint32) Number of colors in the color palette
  16, 0, 0, 0, // 50-53 (4 bytes uint32) Number of important colors used, or 0 when every color is important; generally ignored
// COLOR PALETTE (color array)
  0,   0,   0, 255, // RGB (BGR LE)
  0,   0, 128, 255, // The number of entries is equal to the maximum size possible for the color palette (ncolors = 1 << bpp; or pow(2, bpp);)
  0, 128,   0, 255, // O valor da 4ª coluna deve ser ignorado e intrepretado como padding.
  0, 128, 128, 255, // O valor da 4ª coluna pode, ou deveria, ser 0.
128,   0,   0, 255, // Quando DIB header size == 12 só existem 3 colunas.
128,   0, 128, 255,
128, 128,   0, 255,
128, 128, 128, 255,
192, 192, 192, 255,
  0,  0,  255, 255,
  0, 255,   0, 255,
  0, 255, 255, 255,
255,   0,   0, 255,
255,   0, 255, 255,
255, 255,   0, 255,
255, 255, 255, 255,
// IMAGE DATA (pixel array)
/** Row of pixels (scan-line) ---> (60 pixeis * 4bpp / 8 = 30 bytes)                                                                               */
/** Para 4bpp cada byte contem 2 pixeis                                                                                */
/** 4bpp (1 pixel por cada 4 bits ---> 2 pixeis por byte) (2 nibbles por byte)                                                                     */
/** Row of pixels tem que ser um múltiplo de 8 bits. Exemplo: ((59 pixeis * 4bpp) + 8 - 1 - ((59 pixeis * 4bpp) + 8 - 1) % 8) / 8 = 30 bytes       */
/** Se o valor Width não for múltiplo de 2 o último byte de Row of pixels é composto por 1 nibble-pixel + 1 nibble de valor 0(extra padding nibble)*/
/** Para 4bpp cada nibble-pixel representa um índice referente a uma cor contida na palete de cores                                                */
/** Para extrair 2 nibbles (2 índices) de 1 byte: left_nibble = byte >> 4; right_nibble = byte & 15                                                */
/** Para inverter a ordem nibble de 1 byte (espelhar 1 byte composto por 2 nibbles): (byte & 15) << 4 | (byte >> 4)                                */
/** Para transformar 2 nibbles em 1 byte: (left__nibble << 4) | right_nibble                                                                       */
/** Se o valor Height da imagem for positivo os pixeis são armazenados a partir do canto inferior direito (1º pixel) para o canto superior esquerdo*/
/** Se o valor Height da imagem for negativo os pixeis da imagem são armazenados do canto superior esquerdo para o canto inferior direito          */
/** O valor Height negativo é válido para bitmaps sem compressão e DIB header size > 12                                                            */
/** Para converter um número negativo para 4 bytes LE, por exemplo -60:                                                                            */
/** nB1 = ( -60 ) >> 0 & 255; nB2 = ( -60 ) >> 8 & 255; nB3 = ( -60 ) >> 16 & 255; nB4 = ( -60 ) >> 24 & 255;                                      */
/**/255,/*<--- os últimos 2 pixeis da imagem*/ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, /**/0, 0,/** Padding for 4 byte alignment (scan-line boundary padding), could be a value other than zero. */
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, /**/0, 0,/** Se "Row of Pixels" (scan-line) não for um múltiplo de 4 bytes "Total Row Size" (stride) será (RowOfPixelsize + 4 - 1 - (RowOfPixelsize + 4 - 1) % 4) */
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, /**/0, 0,/** Exemplo: 30 bytes + 4 - 1 - (30 bytes + 4 - 1) % 4 = 32 bytes */
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 131, 153, 153,  51,  59, 184, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 153, 153, 153, 153,  51, 187, 179,  59, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 153, 153, 153, 153,  51, 139, 187, 179, 187,  59, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 153, 153, 153, 143, 255, 255, 255, 255, 248, 179,  59,  59, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 137, 153, 151, 255, 255, 255, 255, 255, 255, 255, 255, 139,  59,  56, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 248, 153, 147, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 179, 179, 143, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 121, 153, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248,  59,  56, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 248, 153, 152, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 179, 143, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 137, 153, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 187,  56, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 153, 152, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 243, 179, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 249, 153, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248,  59, 191, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 137, 147, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 131,  56, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 153, 159, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 187, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 248, 153, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248,  51, 143, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 249, 153, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 179, 191, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 137, 152, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 131,  56, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 153, 159, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251,  59, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 136, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 136, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 119, 143, 255, 255, 119, 143, 255, 248, 119, 255, 119, 119, 127, 255, 248, 119, 119, 143, 248, 119, 255, 255, 247, 120, 247, 120, 255, 255, 0, 0,
255, 255,  64, 127, 255, 255,  68, 111, 255, 244,  68, 244,  68,  68,  68, 143, 128,  68,  68,  70, 248,   0, 127, 255, 132,   7, 244,   6, 255, 255, 0, 0,
255, 255,  68, 127, 255, 255, 116,  79, 255, 244,  71, 246,  70, 102,  68,  79, 132,  70, 100,  68, 127,  68, 111, 255, 116,  72, 246,  70, 255, 255, 0, 0,
255, 255,  68, 127, 255, 255, 132,  70, 102, 100,  72, 255, 255, 255, 100,  15, 248, 255, 248,  68, 111, 116,  70, 103, 100,  79, 246,  70, 255, 255, 0, 0,
255, 255,  68, 127, 255, 255, 244,  68,  68,  68,  79, 255, 255, 255, 116,  15, 255, 255, 255,  68, 111, 132,  68,  68,  68, 111, 246,  70, 255, 255, 0, 0,
255, 255,  68,  68,  70, 143, 246,  68, 119,  68, 127, 255, 248, 118,  68,  79, 255, 248, 118,  68, 111, 244,  70, 119,  68, 143, 246,  70, 255, 255, 0, 0,
255, 255,  68,  68,  68,  72, 247,  68, 255,  68, 143, 255, 100,  68,  68, 127, 248, 100,  68,  68, 143, 246,  70, 247,  68, 255, 246,  70, 255, 255, 0, 0,
255, 255,  68, 103, 116,  68, 255,  68, 136,  68, 255, 246,  68,  68, 104, 255, 244,  68,  68, 104, 255, 247,  68, 246,  70, 255, 246,  70, 255, 255, 0, 0,
255, 255,  68, 127, 246,  68, 255,  68, 119,  70, 255, 244,  68, 143, 255, 255, 132,  70, 255, 255, 255, 255,  68, 132,  71, 255, 246,  70, 255, 255, 0, 0,
255, 255,  68, 127, 246,  68, 255, 116, 100,  71, 255, 244,  70, 255, 255, 255, 116,  72, 255, 255, 255, 255,  68, 116,  72, 255, 246,  70, 255, 255, 0, 0,
255, 255,  68, 103, 116,  68, 255, 132,  68,  72, 255, 244,  68, 119, 118, 143, 132,  68, 119, 118, 255, 255, 116,  68,  79, 255, 246,  70, 255, 255, 0, 0,
255, 255,  68,  68,  68,  72, 255, 244,  68,  79, 255, 247,  68,  68,  64, 111, 246,  68,  68,  64, 143, 255, 132,  68, 127, 255, 244,  70, 255, 255, 0, 0,
255, 255, 102, 102, 102, 143, 255, 247, 102, 127, 255, 255, 134,  68, 102, 143, 255, 118,  68, 103, 255, 255, 246, 100, 143, 255, 246, 103, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 143, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 247,   6, 143, 255, 0, 0,
255, 255, 255, 255, 187, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 102, 255, 100,   8, 255, 0, 0,
255, 255, 255, 255, 139, 184, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 134, 104, 255, 247,  79, 255, 0, 0,
255, 255, 255, 255, 251, 187, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 230, 111, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 248, 187, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 102, 127, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 187, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 102, 143, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 139, 184, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 134, 103, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 251, 187, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 102, 111, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 187, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 102, 143, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 139, 187, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 102, 103, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 251, 187, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 246, 102, 111, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 187, 187, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 102, 102, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 251, 187, 184, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 134, 102, 111, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 187, 187, 184, 255, 255, 255, 255, 255, 255, 255, 255, 134, 102, 102, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 248, 187, 187, 184, 255, 255, 255, 255, 255, 255, 134, 102, 102, 143, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 187, 187, 187, 136, 136, 136, 135, 102, 102, 102, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 187, 187, 187, 187, 102, 102, 102, 102, 104, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 187, 187, 187, 102, 102, 110, 143, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 248, 136, 136, 136, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, /**/255,/*<--- os primeiros 2 pixeis da imagem*/ 0, 0,
};

Answer: "(...) como faço para espelhar uma imagem. (...) Será que tenho que inverter esses bits por linha, para ter o resultado almejado? (...)"
Continuação...
// continuação...
struct BMInfos {
    int isBM;
    int bpp;
    int Width;
    int absHeight;
    int StartOfImageDataOffset;
    int ImageDataSize;
    int TotalRowSize;
    int PixelRowSize;
    int PadSize;
    int isCompressed;
} inf;

void SetInfos() {
    inf.isBM = (icon[0] == 'B' && icon[1] == 'M');
    inf.StartOfImageDataOffset = (icon[10] << 0) | (icon[11] << 8) | (icon[12] << 16) | (icon[13] << 24);
    int dibSize = (icon[14] << 0) | (icon[15] << 8) | (icon[16] << 16) | (icon[17] << 24);
    inf.Width = (dibSize == 12) ? (icon[18] << 0) | (icon[19] << 8) : (icon[18] << 0) | (icon[19] << 8) | (icon[20] << 16) | (icon[21] << 24);
    int Height = (dibSize == 12) ? (icon[20] << 0) | (icon[21] << 8) : (icon[22] << 0) | (icon[23] << 8) | (icon[24] << 16) | (icon[25] << 24);
    inf.absHeight = (Height + (Height >> 31)) ^ (Height >> 31); /** O valor de "Height" pode ser negativo ou positivo. */
    inf.bpp = (dibSize == 12) ? (icon[24] << 0) | (icon[25] << 8) : (icon[28] << 0) | (icon[29] << 8);
    int Compression = (dibSize != 12) ? (icon[30] << 0) | (icon[31] << 8) | (icon[32] << 16) | (icon[33] << 24) : 0;
    inf.isCompressed  = (!(Compression == 0 || (Compression == 3 && (inf.bpp == 16 || inf.bpp == 32))));
    inf.ImageDataSize = ((((inf.Width * inf.bpp) + 31) & ~31) >> 3) * inf.absHeight;
    inf.PixelRowSize  = ((((inf.Width * inf.bpp) +  7) &  ~7) /  8); /** Tem que ser um múltiplo de 8 bits. (scan-ine)*/
    inf.TotalRowSize  = ((((inf.Width * inf.bpp) + 31) & ~31) >> 3); /** Tem que ser um múltiplo de 4 bytes. (stride)*/
    inf.PadSize = inf.TotalRowSize - inf.PixelRowSize; /** Os valores byte de prenchimento de linha para TotalRowSize "padding for 4 byte alignment" podem ser zero(s) ou qualquer outro valor. */
    int extraPaddingBitLevel = ((inf.PixelRowSize * 8) - (inf.Width * inf.bpp)) / inf.bpp; /** n bits|nibbles de prenchimento (nível bit) para PixelRowSize, "padding for 8 bit alignment". */

    printf( "\nBits per pixel: %d bpp", inf.bpp );
    printf( "\nImage width: %d pixels", inf.Width );
    printf( "\nImage height: %d pixels", inf.absHeight );
    printf( "\nStart of image data offset: %d", inf.StartOfImageDataOffset );
    printf( "\nImage data size: %d bytes", inf.ImageDataSize );
    printf( "\nTotal row size: %d bytes", inf.TotalRowSize );
    printf( "\nPixel row size: %d bytes", inf.PixelRowSize );
    printf( "\nPadding size: %d bytes", inf.PadSize );
    printf( "\nExtra padding, bit level: %d %s", extraPaddingBitLevel, inf.bpp == 1 ? "bits" : inf.bpp == 4 ? "nibbles" : "" );
    printf( "\nCompression value: %d", Compression );
    printf( "\nIs compressed: %s\n", inf.isCompressed ? "true" : "false" );
}

void Mirror() { // Espelhar um bitmap na horizontal
    int s = inf.StartOfImageDataOffset;
    int e = inf.StartOfImageDataOffset + (inf.ImageDataSize - 1) - inf.PadSize;

    if (inf.bpp == 1) {
        /** 1bpp (8 pixels por byte ---> 1 pixel por cada bit) (2 cores indexadas RGB (BGR LE)) */
        char auxT[inf.ImageDataSize * 8];
        int extraPaddingBits = ((inf.PixelRowSize * 8) - (inf.Width * inf.bpp)) / inf.bpp; /** Extra "padding", nível bit. Se existir, ... */
        /** ... por exemplo quando o valor "Width" da imagem não é um múltiplo de 8 os últimos bit-pixeis de cada linha de pixeis não cabem em 1 byte completo sendo este último byte constituído por n bit-pixeis + n bits de valor 0. */

        /** Converte todas as sequências byte em bit-pixeis (índices) invertendo a sua ordem por linha mas mantendo os bits de preenchimento no final de cada linha. Todos os bits serão armazenados temporariamente em auxT. */
        int k = 0;
        while (s <= e) {
            int i = 0;
            int j = inf.PixelRowSize;
            while (j--) {
                int l = (extraPaddingBits != 0 && i == 0) ? extraPaddingBits : 0; /** Mantêm os bits de preenchimento (nível bit) no final da linha de pixeis, se existirem. */
                while (l < 8) {
                    auxT[k + i] = icon[s + j] >> l & 1;
                    i++;
                    l++;
                }
            }
            s += inf.TotalRowSize;
            k += inf.TotalRowSize * 8;
        }
        /** Converte os bits para bytes e armazena-os nos dados da imagem */
        s = 0;
        e = sizeof(auxT) - 1;
        k = inf.StartOfImageDataOffset;
        while (s <= e) {
            char bit7 = auxT[s + 0];
            char bit6 = auxT[s + 1];
            char bit5 = auxT[s + 2];
            char bit4 = auxT[s + 3];
            char bit3 = auxT[s + 4];
            char bit2 = auxT[s + 5];
            char bit1 = auxT[s + 6];
            char bit0 = auxT[s + 7];
            icon[k] = (bit7 << 7) | (bit6 << 6) | (bit5 << 5) | (bit4 << 4) | (bit3 << 3) | (bit2 << 2) | (bit1 << 1) | (bit0 << 0);
            s += 8;
            k++;
        }
    }

    if (inf.bpp == 4) {
        /** 4bpp (2 pixeis por byte ---> 1 pixel por cada 4 bits) (2 nibbles por byte) (16 cores indexadas RGB (BGR LE)) */
        char auxT[inf.ImageDataSize * 2];
        int extraPaddingNibble = ((inf.PixelRowSize * 8) - (inf.Width * inf.bpp)) / inf.bpp; /** Extra "padding", nível bit. Se existir, ... */
        /** ... por exemplo quando o valor "Width" da imagem não é um múltiplo de 2 o último nibble-pixel de cada linha de pixeis não cabe em 1 byte completo sendo este último byte constituído por 1 nibble-pixel + 1 nibble de valor 0. */

        /** Converte todas as sequências byte em nibble-pixeis (índices) invertendo a sua ordem por linha mas mantendo os nibbles de preenchimento no final de cada linha. Todos os nibbles serão armazenados temporariamente em auxT. */
        int k = 0;
        while (s <= e) {
            int i = 0;
            int j = inf.PixelRowSize;
            while (j--) {
                if (!(extraPaddingNibble != 0 && i == 0)) auxT[k + i++] = icon[s + j] & 15; /** Mantêm o nibble de preenchimento (nível bit) no final da linha de pixeis, se existir. */
                auxT[k + i++] = icon[s + j] >> 4;
            }
            s += inf.TotalRowSize;
            k += inf.TotalRowSize * 2;
        }
        /** Converte as sequências nibble para byte e armazena todos os bytes nos dados da imagem */
        s = 0;
        e = sizeof(auxT) - 1;
        k = inf.StartOfImageDataOffset;
        while (s <= e) {
            icon[k] = (auxT[s + 0] << 4) | auxT[s + 1];
            s += 2;
            k++;
        }
    }

    if (inf.bpp >= 8) {
        /** 8bpp (1 pixel por byte ---> 1 pixel por cada 8bits) (256 cores indexadas RGB (BGR LE)) */
        /** 16bpp RGB ou ARGB (BGR ou BGRA LE) (1 pixel por cada 2 bytes ----> 1 pixel por cada 16 bits) (até 65536 cores únicas não indexadas) */
        /** 24bpp RGB (BGR LE) (1 pixel por cada 3 bytes ----> 1 pixel por cada 24 bits) (até 16777216 cores únicas não indexadas) */
        /** 32bpp ARGB (BGRA LE) (1 pixel por cada 4 bytes ----> 1 pixel por cada 32 bits) (até 4294967296 cores únicas não indexadas) */

        /** A partir de 8bpp todas as sequências índice (8bpp), RBG (16 e 24bpp) ou ARGB (16 e 32bpp) cabem em bytes completos. */
        /** A regra "padding for 4 byte alignment" continua a ser válida para 8, 16 e 24bpp. */
        /** 32bpp contêm naturalmente sequências de 4 bytes (1 B + 1 G + 1 R + 1 byte para o canal Alpha = 4 bytes). 32bpp nunca terá "paddings". */
        char b0, b1, b2, b3;
        int l, r, u, v, w;
        while (s <= e) {
            l = 0;
            r = inf.PixelRowSize - 1;
            while (l <= r) {
                                                   u = 0, w = 0;
                               if (inf.bpp >=  8) b0 = icon[s + l + u++];
                               if (inf.bpp >= 16) b1 = icon[s + l + u++];
                               if (inf.bpp >= 24) b2 = icon[s + l + u++];
                               if (inf.bpp >= 32) b3 = icon[s + l + u++];
                                                   v = u;
                if (inf.bpp >=  8) icon[s + l + w++] = icon[s + r - --u];
                if (inf.bpp >= 16) icon[s + l + w++] = icon[s + r - --u];
                if (inf.bpp >= 24) icon[s + l + w++] = icon[s + r - --u];
                if (inf.bpp >= 32) icon[s + l + w++] = icon[s + r - --u];
                if (inf.bpp >=  8) icon[s + r - --w] = b0;
                if (inf.bpp >= 16) icon[s + r - --w] = b1;
                if (inf.bpp >= 24) icon[s + r - --w] = b2;
                if (inf.bpp >= 32) icon[s + r - --w] = b3;
                l += v;
                r -= v;
            }
            s += inf.TotalRowSize;
        }
    }
}

void Flip() { // Espelhar um bitmap verticalmente
    int s = inf.StartOfImageDataOffset;
    int e = inf.StartOfImageDataOffset + inf.ImageDataSize;
    while (s < e) {
        int u = inf.TotalRowSize;
            while (u--) {
                                       char b0 = icon[s + u];
                                   icon[s + u] = icon[e - inf.TotalRowSize + u];
                icon[e - inf.TotalRowSize + u] = b0;
            }
        s += inf.TotalRowSize;
        e -= inf.TotalRowSize;
    }
}

void DIBFlip() { // Espelhar um bitmap verticalmente invertendo o sinal do valor "Height"
    int dibSize = (icon[14] << 0) | (icon[15] << 8) | (icon[16] << 16) | (icon[17] << 24);
    if (dibSize == 12) return; /** DIB Filp incompativel com OS/2 1.x BITMAPCOREHEADER (dibSize == 12) */
    int Height  = (icon[22] << 0) | (icon[23] << 8) | (icon[24] << 16) | (icon[25] << 24);
    int dib_flip = -(Height); /** Inverte o sinal do valor Height da imagem. */
    icon[22] = dib_flip >>  0 & 255;
    icon[23] = dib_flip >>  8 & 255;
    icon[24] = dib_flip >> 16 & 255;
    icon[25] = dib_flip >> 24 & 255;
}

void MirrorFlip() { // Espelhar um bitmap na horizontal e na vertical ao mesmo tempo
    int s = inf.StartOfImageDataOffset;
    int e = inf.StartOfImageDataOffset + (inf.ImageDataSize - 1) - inf.PadSize;

    /*
    if (inf.bpp == 1) { // Implementação mais simples, mas não funciona corretamente se o "Width" da imagem não for múltiplo de 8.
        // 1bpp (8 pixels por byte ---> 1 pixel por cada bit) (até 2 cores indexadas RGB (BGR LE))
        while (s <= e) {
            char b0 = icon[s];
            char b1 = icon[e];
               icon[s] = (b1 & 128) >> 7 | (b1 & 64) >> 5 | (b1 & 32) >> 3 | (b1 & 16) >> 1 | (b1 & 8) << 1 | (b1 & 4) << 3 | (b1 & 2) << 5 | (b1 & 1) << 7;
               icon[e] = (b0 & 128) >> 7 | (b0 & 64) >> 5 | (b0 & 32) >> 3 | (b0 & 16) >> 1 | (b0 & 8) << 1 | (b0 & 4) << 3 | (b0 & 2) << 5 | (b0 & 1) << 7;
            s++;
            e--;
        }
    }
    */

    if (inf.bpp == 1) {
        /** 1bpp (8 pixels por byte ---> 1 pixel por cada bit) (2 cores indexadas RGB (BGR LE)) */
        char auxT[inf.ImageDataSize * 8];
        int extraPaddingBits = ((inf.PixelRowSize * 8) - (inf.Width * inf.bpp)) / inf.bpp; /** Extra "padding", nível bit. */
        /** Converte todas as sequências byte em bit-pixeis (índices) invertendo totalmente a sua ordem mas mantendo os bits de preenchimento no final de cada linha. Todos os bits serão armazenados temporariamente em auxT. */
        int k = 0;
        while (s <= e) {
            int j = (extraPaddingBits != 0 && k == 0) ? extraPaddingBits : 0; /** Mantêm os bits de preenchimento (nível bit) no final da linha de pixeis, se existirem. */
            while (j < 8) {
                auxT[k] = icon[e] >> j & 1;
                j++;
                k++;
            }
            e--;
        }
        /** Converte os bits para bytes e armazena-os nos dados da imagem */
        /** Durante o processo de conversão eventuais bytes de preenchimento, "padding for 4 byte alignment", poderão adquirir novos valores diferentes dos seus valores originais. Estes, possíveis, novos valores não são importantes. */
        s = 0;
        e = sizeof(auxT) - 1;
        k = inf.StartOfImageDataOffset;
        while (s <= e) {
            char bit7 = auxT[s + 0];
            char bit6 = auxT[s + 1];
            char bit5 = auxT[s + 2];
            char bit4 = auxT[s + 3];
            char bit3 = auxT[s + 4];
            char bit2 = auxT[s + 5];
            char bit1 = auxT[s + 6];
            char bit0 = auxT[s + 7];
            icon[k] = (bit7 << 7) | (bit6 << 6) | (bit5 << 5) | (bit4 << 4) | (bit3 << 3) | (bit2 << 2) | (bit1 << 1) | (bit0 << 0);
            s += 8;
            k++;
        }
    }

    /*
    if (inf.bpp == 4) { // Implementação mais simples, mas não funciona corretamente se o "Width" da imagem não for múltiplo de 2.
        // 4bpp (2 pixeis por byte ---> 1 pixel por cada 4 bits) (2 nibbles por byte) (até 16 cores indexadas RGB (BGR LE))
        while (s <= e) {
            char b0 = icon[s];
               icon[s] = (icon[e] & 15) << 4 | (icon[e] >> 4);
               icon[e] = (     b0 & 15) << 4 | (     b0 >> 4);
            s++;
            e--;
        }
    }
    */

    if (inf.bpp == 4) {
        /** 4bpp (2 pixeis por byte ---> 1 pixel por cada 4 bits) (2 nibbles por byte) (16 cores indexadas RGB (BGR LE)) */
        char auxT[inf.ImageDataSize * 2];
        int extraPaddingNibble = ((inf.PixelRowSize * 8) - (inf.Width * inf.bpp)) / inf.bpp; /** Extra "padding", nível bit. */
        /** Converte todas as sequências byte em nibble-pixeis (índices) invertendo totalmente a sua ordem mas mantendo os nibbles de preenchimento no final de cada linha. Todos os nibbles serão armazenados temporariamente em auxT. */
        int k = 0;
        while (s <= e) {
            if (!(extraPaddingNibble != 0 && k == 0)) auxT[k++] = icon[e] & 15; /** Mantêm o nibble de preenchimento (nível bit) no final da linha de pixeis, se existir. */
            auxT[k++] = icon[e] >> 4;
            e--;
        }
        /** Converte as sequências nibble para byte e armazena todos os bytes nos dados da imagem */
        /** Durante o processo de conversão eventuais bytes de preenchimento, "padding for 4 byte alignment", poderão adquirir novos valores diferentes dos seus valores originais. Estes, possíveis, novos valores não são importantes. */
        s = 0;
        e = sizeof(auxT) - 1;
        k = inf.StartOfImageDataOffset;
        while (s <= e) {
            icon[k] = (auxT[s + 0] << 4) | auxT[s + 1];
            s += 2;
            k++;
        }
    }

    if (inf.bpp >= 8) {
        /** 8bpp (1 pixel por byte ---> 1 pixel por cada 8bits) (256 cores indexadas RGB (BGR LE)) */
        /** 16bpp RGB ou ARGB (BGR ou BGRA LE) (1 pixel por cada 2 bytes ----> 1 pixel por cada 16 bits) (até 65536 cores únicas não indexadas) */
        /** 24bpp RGB (BGR LE) (1 pixel por cada 3 bytes ----> 1 pixel por cada 24 bits) (até 16777216 cores únicas não indexadas) */
        /** 32bpp ARGB (BGRA LE) (1 pixel por cada 4 bytes ----> 1 pixel por cada 32 bits) (até 4294967296 cores únicas não indexadas) */

        /** A partir de 8bpp todas as sequências índice (8bpp), RBG (16 e 24bpp) ou ARGB (16 e 32bpp) cabem em bytes completos. */
        /** A regra "padding for 4 byte alignment" continua a ser válida para 8, 16 e 24bpp. */
        /** Os eventuais bytes de preenchimento, "padding for 4 byte alignment", são facilmente mantidos no final de cada linha bastando para isso criar um desfasamento no valor "end" do laço while ou for: e = inf.StartOfImageDataOffset + (inf.ImageDataSize - 1) - inf.PadSize;. */
        int u, v, w;
        char b0, b1, b2, b3;
        while (s <= e) {
                                           u = 0, w = 0;
                       if (inf.bpp >=  8) b0 = icon[s + u++];
                       if (inf.bpp >= 16) b1 = icon[s + u++];
                       if (inf.bpp >= 24) b2 = icon[s + u++];
                       if (inf.bpp == 32) b3 = icon[s + u++];
                                           v = u;
            if (inf.bpp >=  8) icon[s + w++] = icon[e - --u];
            if (inf.bpp >= 16) icon[s + w++] = icon[e - --u];
            if (inf.bpp >= 24) icon[s + w++] = icon[e - --u];
            if (inf.bpp == 32) icon[s + w++] = icon[e - --u];
            if (inf.bpp >=  8) icon[e - --w] = b0;
            if (inf.bpp >= 16) icon[e - --w] = b1;
            if (inf.bpp >= 24) icon[e - --w] = b2;
            if (inf.bpp == 32) icon[e - --w] = b3;
            s +=  v;
            e -=  v;
        }
    }
}

void SaveFile(char fname[]) {
    FILE *fout = fopen(fname, "wb");
    fwrite(icon, sizeof(icon), 1, fout);
    fclose(fout);
}

void Choice() {
    printf( "\nPress: 1 to Mirror | 2 to Mirror-Flip | 3 to Flip | 4 to DIB-Flip | 5 to Exit.\n" );
    char r;
    gets(&r);
    switch (r) {
        case '1':
            Mirror();
            SaveFile("Mirror.bmp");
            break;
        case '2':
            /*
            Mirror();
            Flip();
            SaveFile();
            */
            MirrorFlip();
            SaveFile("Mirror-Flip.bmp");
            break;
        case '3':
            Flip();
            SaveFile("Flip.bmp");
            break;
        case '4':
            DIBFlip();
            SaveFile("DIB-Flip.bmp");
            break;
        case '5':
            return;
        default:
            Choice();
    }

    printf("Continue... [y,n]?\n");
    gets(&r);
    switch (r) {
        case 'y':
            Choice();
            break;
        default:
            return;
    }
}

int main() {
    SetInfos();
    if (!inf.isBM) return -1; // O arquivo está danificado ou não é suportado.
    if (inf.Width < 0) return -1; // Tem que ser positivo (mandatório).
    if (inf.isCompressed) return -1; // Não suporta compressão.
    if (inf.bpp == 2) return -1; // Não suporta 2bpp.
    Choice();
    return 0;
}

Como espelhar uma imagem?


Proving $\lim_{x \to 2}x^2 = 4$ true

Question: I have this limit: $\lim_{x \to 2}x^2 = 4$ and I want to prove it, so I solve $|f(x)-l|<\epsilon$
$|x^2-2|<\epsilon$
$2-\epsilon<x^2<2+\epsilon$
and here I don't know what to do, can you help me?
Comment: At the very least you want to be looking at $|x^2 - 4\$ with $|x- 2|<\delta$.
Comment: While it's $x\to7$ instead, have a look at my answer here: https://math.stackexchange.com/questions/2373285/limits-by-definition-a-conceptual-doubt/2373315 It should tell you everything you need to know. I'm sure this exact question, perhaps with other numbers in place of $2$ or $7$, has been asked a lot of other times as well.
Comment: @S.vanNigtevecht Yes I'm sorry! I meant to say that
Comment: you need to show that $|x^2-4|<\varepsilon$, and here's a hint : $x^2-4=(x-2)(x+2)$.
Comment: @yanko I think I need the full proof :(
Comment: The proof is in your earlier question https://math.stackexchange.com/questions/2391382/how-to-prove-lim-x-to-2-x2-4-and-make-sure-its-correct, isn't it?
Answer: Given $\epsilon>0$,  you look for $\delta $ such that
$$|x-2|<\delta \implies |\color {green}{x+2} ||x-2|<\epsilon $$
As $x $ goes to $2$, it means that $x $ is not far from $2$, so we can assume that $$|x-2|<\color {red}{1} $$
$$\implies -1 <x-2 <1 $$
$$\implies 3 <\color {green}{x+2} <5$$
$$\implies$$
$$ |x^2-4|=|\color {green}{x+2}||x-2|<5|x-2|.$$
thus
$\Bigl (5|x-2|<\epsilon $ and $|x-2|<\color {red}{1} $
$\implies |x^2-4|<\epsilon\Bigr) $.
To satisfy this last condition, we need
$|x-2|<\frac {\epsilon}{5} $ and $|x-2|<\color {red}{1} $
hence we will take $\delta=\min (\frac {\epsilon}{5},\color {red}{1}) $.
Comment: if this is hint,what is the prove? :)
Comment: It's a very substantial hint. I would say it's so substantial it doesn't deserve the name "hint".
Comment: you have a typo: a limit is defined by $0<|x-2|<\delta$, you mixed with the definition of continuity that is $|x-2|<\delta$
Comment: @Masacroso No typo. here $f (2) $ is defined $(=4) $ so no problem.
Comment: @Salahamam_Fatima Yes typo (or an actual mistake, if that is to your liking). Here the assignment is to check the limit as $x\to2$, not continuity at $x=2$. That means $0<|x-2|$ regardless of whether it works without it.
Comment: @Arthur $f (2) =4$  so if $|x-2|=0$ then $|f (2)-4|=0<\epsilon $. BUT YOU ARE RIGHT.
Comment: It is true that continuity at $a$ requires more than that the limit exists. But this means that establishing continuity also shows the limit exists and is $f(a).$

Proving $\lim_{x \to 2}x^2 = 4$ true


Estimate conversion rate over time using different overall mean

Question: I have to estimate conversion rate of visitors of a website for the next day.
The forecasted value has several input parameters:

Website
is Weekend/Workday (Yes, No),
Month (1-12)
Week of the year (1-52)

I have historical data in a table like this

Website
Weekend/Workday
Month
Week of the year
Clicks
Orders
Conversion rate

Google.it
Weekend
12
50
10
1
10%

Google.it
Workday
10
40
100
5
5%

Google.it
Workday
1
3
20
1
5%

Now I can compute the overall mean for each when I sum clicks/orders by each paramenter and calculate the historical conversion rate.
For example, aggregating by weekend/workday I can get

Website
Weekend/workday
clicks
Orders
Conversion rate

Google.it
Workday
120
6
5%

Google.it
Weekend
10
1
10%

or by month

Website
Month
clicks
Orders
Conversion rate

Google.it
1
20
1
5%

Google.it
10
100
5
5%

Google.it
12
10
1
10%

Now my question is, what model could I use to estimate the conversion rate for the next data point having as input all those overall means?
For example, I would estimate the conversion rate for tomorrow (Workday/Weekend=Workday, month=11, Week=45) = ?
My idea is to calculate the overall mean by website (all time conversion rate) and then isolate the effect of weekends, month and Week seasonalities. But I have more components of seasonality and they are dependent each other so I don't know how to do it.
Comment: To me, the question is poorly stated. Could it be due to a lack of understanding of the topics involved? Is this AB testing or Logit,..., I don't see any mention of either. Think back to your original question. What is important to investigate? If this is due tomorrow then may I suggest starting with taking the entire dataset and doing one test by whatever test looks most appropriate in your situation. Again, you need to sharpen yr question.
Comment: How does it look like when you plot it as a time series? E.g. the conversion rate on weekdays or weekends as function of the week. If that looks like a well behaved function then fit some reasonable estimate and extrapolate it.
Comment: Yes, sorry I don't know much about topic I would like a direction. It's not A/B testing, is forecasting a new conversion rate.
Answer: I recommend fitting a logistic regression model.  It could be much more complicated than this, and could incorporate more seasonality components if desired.
$$\rm \ln\left(\frac{\frac{orders}{clicks}}{1-\frac{orders}{clicks}} \right) = \beta_0 + \beta_1 type + \beta_2 week + \beta_3 month$$
where $\beta_1$ is a coefficient on type={0,1}, $\beta_2$ is really a family of coefficients on a dummy encoded week, and $\beta_3$ is a family of coefficients on a dummy encoded month.
Here is how that is accomplished in R:
<code>require(lubridate)

# simulate data
set.seed(18093)
data <- data.frame(website = factor(rep(c("google", "yahoo", "apple"), times = 180)),
                   date = rep(as.Date("2022-01-01")+1:60, each = 3),
                   clicks = rpois(180*3, 100),
                   orders = rbeta(180*3, 1, 10))
data$orders <- floor(data$orders * data$clicks)
data$rate <- data$orders / data$clicks
data$type <- factor(ifelse(lubridate::wday(data$date, label = TRUE) %in% c("Sat","Sun"), "Weekend", "Weekday"))
data$month <- factor(lubridate::month(data$date, label = TRUE))
data$week <- factor(lubridate::week(data$date))

# fit a generalized linear model
glm1 <- glm(cbind(orders, clicks) ~ type + month + week, family = binomial(link = "logit"),
            data = data)

# predict on a new day  Google, Weekday, week 7, month Feb
predict(glm1, newdata = data.frame(website = factor("google", levels = levels(data$website)),
                               type = factor("Weekday", levels = levels(data$type)),
                                   week = factor(7, levels = levels(data$week)),
                               month = factor("Feb", levels = levels(data$month))),
        type = "response")
#>          1
#> 0.09054071
</code>
Created on 2022-11-18 with reprex v2.0.2
Comment: OP, a logistic regression model exactly does exactly what you are after - incorporating the effect of each variable, whilst taking account of the dependencies between variables


$\lim_{n \rightarrow \infty}\left(1+\dfrac{2}{n}\right)^{n^2}e^{-2n}$

Question: $\lim_{n \rightarrow \infty}\left(1+\dfrac{2}{n}\right)^{n^2}e^{-2n}$
$\lim_{n \rightarrow \infty}\left(e^{-2}\left(1+\dfrac{2}{n}\right)^n\right)^{n}$
It is indeterminate form $1^{\infty}$
I solve this like this $e^{\lim_{n \rightarrow \infty}}\frac{\ln(e^{-2}(1+\frac{2}{n})^n)}{\frac{1}{n}}$
I can't apply L'Hôpital's rule now how can I solve this problem quickly?
Comment: You seemingly had a typo in the title which I corrected. Let me know if it is not what you wanted.
Answer: You have :
$$\left(1+\dfrac{2}{n}\right)^{n^2}=\exp\left(n^2\log\left(1+\frac{2}{n}\right)\right)=\exp\left(n^2\left(\frac{2}{n}-\frac{4}{2n^2}+o\left(\frac{1}{n^2}\right)\right)\right)\\=\exp\left(2n-2+o\left(1\right)\right)$$
So you get :
$$\left(1+\dfrac{2}{n}\right)^{n^2}e^{-2n}=e^{-2+o(1)} $$
So you get the final result :
$$\lim_{n \rightarrow \infty}\left(1+\dfrac{2}{n}\right)^{n^2}e^{-2n}=e^{-2} $$
Answer: Just a brief explanation about the answer above:
Observe that
$$\log(1+x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \ldots .$$
Then, it's clear that (for $x = \frac{2}{n}$)
$$\log\left(1 + \frac{2}{n}\right) = \frac{2}{n} - \frac{4}{2n^2} + \ldots .$$
Comment: I think it's better, because in chat we can't see the preview of answer.
Comment: You could have added this as a *comment* to the other answer rather than posting it as a separate one.


Intellij: Run button disabled for tcServer

Question: I am new to IntelliJ and trying to get my web application to launch using tcServer
I am using a local configuration, and have added a run configuration. See attached screenshots
However, when I attempt to run this, the Run button is disabled.
What am I missing here?
Answer: You have edited a default configuration, you did not add a new runnable server configuration. In order to do that click on the green + sign at the top left of the run screen.
You should remove the war from the default configuration and add it in the newly created server.
see attached, screenshot, you can see the difference between a default and a runnable configuration
Answer: It seems you have to use the little green "+" in the upper left corner. The one you edited is just the default setting for your spring server. If you add a specific run configuration like that to your project it will appear. Good luck.
Comment: Thanks, I was stuck there for hours.
Why did someone put a disabled run button on a template which is not something that can be actually run?


How to set the CSS with Spring Boot and Thymeleaf

Question: I've been trying to make my css file work with Spring Boot and Thymeleaf (or even without Thymeleaf) but its not working at all.
I've checked many answers on StackOverFlow, tried everything, but its still not working. Here's a sample of what I've done:
My test.html :
<!doctype>

    <meta charset="UTF-8" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />

trololo

index.css :
* {
    margin: 0;
    padding: 0;
}

.test {
    color: red;
}

With thymeleaf, I also tried :
<link rel="stylesheet" type="text/css" th:href="@{/css/index.css}" />

My css file is in resources/static/css/index.css (I've tried that since that's what people from stackoverflow suggested), but no luck.
I also have a SecurityController :
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll();
    }
}

Only warning I managed to grab from the terminal is this one :
2020-07-22 05:19:51.148  WARN 42426 --- [nio-8080-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /css/index.css]
2020-07-22 05:19:51.166  WARN 42426 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound             : No mapping for GET /favicon.ico
2020-07-22 05:19:51.166  WARN 42426 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /favicon.ico]

My application.properties :
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

If you ever faced the same issue, I'd love to get help.
Thanks!
EDIT : Found something. I've posted it below.
Comment: You should post your solution as an answer, instead of leaving the answer in the question. This will help other people to find your solution, in the future. (Maybe you can also add a sentence, explaining why it fixes the issue.)
Comment: @andrewjames : Yes you're right, I should've done that, sorry! As for explaining why it fixes the issue, I absolutely have no idea and I don't want to mislead people.
Answer: Seems like the following line in "application.properties" was the problem :
spring.resources.add-mappings=false

Now it's working! I'd love to explain why it fixed the issue, but as I have no idea, I better leave it like that. Still hope it'll help some of you!


What the notation $A\triangle B$ means?

Question: Reading some notes on point-set topology I saw the notation $A\triangle B$ in one exercise, without any explanation of what the notation means. In this case $A$ and $B$ are sets. To provide the full context, the exercise was:

Let $X$ be a finite set, show that
$$d(A,B)= \# A\triangle B$$
is a metric.

In that case, is the notation $A\triangle B$ somehow standard? If it is, what this notation means?
Answer: $A\Delta B$ is the symmetric difference of the sets $A$ and $B$, the set of elements that are in exactly one of $A$ and $B$. It is also equal to $(A\cup B)\setminus (A\cap B)$.
So $\#(A\Delta B)$ is the cardinality of the set $A\Delta B$, since the ground set is finite, this is just an integer.
Answer: $A\Delta B = (A \cap \bar{B}) \cup (\bar{A} \cap B)$
edit: Which is the same as CoS answer, but written differently.
Comment: what is $\overline B$ ? Is it  the complement of $B$?
Comment: @CarryonSmiling Yes.
Answer:
The picture depicts the "symmetric difference $A \triangle B$" of two set A and B.

What the notation $A\triangle B$ means?


Configure nginx to forward external port to same internal port

Question: I'm running TileMill, which is listening to port 20008 and 20009, from localhost. I want 20009 to be only accessed through nginx on port 80 (with simple auth). I want 20008 to be accessible "directly" from the outside.
server {
   listen 80;
   server_name localhost;
   location / {
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:20009;
        auth_basic "Restricted";
        auth_basic_user_file htpasswd;
    }
}
server {
   listen 20008;
   server_name localhost;
   location / {
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:20008;
    }
}

The obvious problem is that nginx can't listen on port 20008 - it's already being used by TileMill.
Restarting nginx: nginx: [emerg] bind() to 0.0.0.0:20008 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:20008 failed (98: Address already in use)

Is there a way where nginx can listen externally without conflicting with the other service listening internally? (Changing localhost to the server's external IP didn't work.)
Answer: Change your listen statement to include your external IP, eg:
listen 18.104.22.168:20008;
Comment: Yeah, sorry, I misread - deleted my comment now.


Regression algorithm on [0,1] with lots of mislabeled data

Question: I have a training set mapping some Likert-scale variables (integers between 1 and 7, rescaled to real numbers between 0 and 1) to predict a continuous variable between 0 and 1. The data set is reasonable large ($10^4$-$10^5$ rows) but very noisy (5-20% has bogus labeling).
When applying regression algorithms to this dataset, the regression algorithm predicts scores only in a subinterval of [0,1], e.g. scores below 0.1 and above 0.9 are not reached for any input value of the columns. This is expected given the bogus labels; but also inacceptable, as the prediction for non-bogus rows is severely impacted. Moreover, since 0.0 and 1.0 are the most common target values in the training set (it is a 'How much ... are you?' type prediction) it is not appreciated by the users that 0.0 and/or 1.0 would be unreachable. (Simply stretching the result to cover [0,1] greatly increases the error, so is probably suboptimal.)
What method could I use to detect and remove these mislabeled/bogus rows, or at least a significant amount of them? Since they are a minority, I would think something with majority voting should be the answer, but it's not clear how to implement such an approach, since $7^{n_{cols}} > n_{rows}$.
Answer: Since you seem to have enough data, RANSAC could be a good option. That is, we treat the noisy data as outliers. The idea of RANSAC is to iteratively detect those outliers and discard them from the fitting. It is extensively used in image processing for tasks like camera calibration and segmenting primitives like planes in a 3D point cloud, with very good results, because it is able to handle a high rate of outliers, when there are enough data points (as it is your case).
For the sake of completeness, let me copy verbatim the description of the algorithm from Wikipedia (a more detailed though still accessible introduction can be found in RANSAC for dummies by M. Zuliani.
<code>    Given:
        data – a set of observations
        model – a model to explain observed data points
        n – minimum number of data points required to estimate model parameters
        k – maximum number of iterations allowed in the algorithm
        t – threshold value to determine data points that are fit well by model
        d – number of close data points required to assert that a model fits well to data

    Return:
        bestFit – model parameters which best fit the data (or nul if no good model is found)

    iterations = 0
    bestFit = nul
    bestErr = something really large
    while iterations < k {
        maybeInliers = n randomly selected values from data
        maybeModel = model parameters fitted to maybeInliers
        alsoInliers = empty set
        for every point in data not in maybeInliers {
            if point fits maybeModel with an error smaller than t
                add point to alsoInliers
        }
        if the number of elements in alsoInliers is > d {
            % this implies that we may have found a good model
            % now test how good it is
            betterModel = model parameters fitted to all points in maybeInliers and alsoInliers
            thisErr = a measure of how well betterModel fits these points
            if thisErr < bestErr {
                bestFit = betterModel
                bestErr = thisErr
            }
        }
        increment iterations
    }
    return bestFit
</code>
Answer: Considering the size of the Dataset Mentioned by you can use Heterogenous Ensemble, Homogenous Ensemble or Edited Nearest Neighbors for Filtering the noise in the Data.
The homogeneous ensemble is inspired by Cross-Validated Committees Filter[1]. At noise levels approximately more than 10% Heterogenous Ensemble performs worse than Homogenous Ensemble.
So you should use Homogenous Ensemble to filter the noise. You can use Apache-Spark to implement this model.
Here is the algorithm for this method:

Input: data consisting of labels and features
Input: P= the number of partitions
Input: n= Trees the number of trees for Random Forest
Input: e= error tolerance (0<e<1)
Output: the filtered data without noise
partitions ← kFold(data, P)
filteredData ← NULL
for all train, test in partitions do
        rfModel ← random Forest(train, n
Trees)
        rfPred ← predict(rfModel, test)
      joinedData ← join(zipWithIndex(test),
zipWithIndex(rfPred))
       markedData ←
       map original, prediction ∈ joinedData
       if label(prediction)-(label(prediction)) *e < label(original) < label(prediction)+
     (label(prediction))*e then
          original
      else
          (label = NULL, features(original))
      end if
end map
filteredData ← union(filteredData, markedData)
end for
return(filter(filteredData, label != NULL))

[1]        [C.E. Brodley, M.A. Friedl. Identifying Mislabeled Training Data. Journal of Artificial Intelligence Research 11 (1999) 131-167 doi: 10.1613/jair.606]
Comment: I think it is better to check this study to get a better intuition: http://file.scirp.org/pdf/OJS20110300008_18086118.pdf. I think it is mostly fine in practice to use either OOB or proper cross validation. However, in cross-validation your test/val fold is always unique, and so is your training set, so it gives you a better idea (less biased) on how it would generalize on unknown data. But in practice, with enough trees in your forest, it should not be an issue in general.
Comment: @Tom care to elaborate why you believe this to be the case? Oob doesn't use the row at hand for training, so should be equally robust as a proper k-fold, from what I understand.
Comment: (1) Why use k-fold validation with random forests instead of the inherent out of bag prediction? It's not clear to me what the benefit would be.

(2) Since this is a regression problem, not a classification problem, `label(original) = label(prediction)` is an extremely rare condition that will likely miss 100% of my data. Any suggestions on how to do this for regression? I could of course replace it by `abs(label(original)-label(prediction))<0.5` but that seems rather arbitrary; especially the constant.
Comment: You are right, I have corrected the algorithm so it can be used in a regression model. You have to choose the error tolerance though. I suggest choosing a value which does not deplete your data set by a large amount.
Comment: Using a proper k-fold validation is usually better (i.e, more robust) than in built out of bag.


storing output of one file in another file using java

Question: Here in this code some operations are done with using one file (new.txt)
I want to store the output of below code in another file....
public static void main(String a[]) throws Exception {
    try {
        Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
                .replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
                .split("1003.*?1002")) // split on end-to-start-of-next
                .forEach(System.out::println);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Answer: As you already kept the entire file contents in memory, a non-stream solution is more straight-forward.
String txt = new String(Files.readAllBytes(Paths.get("in.txt")), StandardCharsets.UTF_8);
txt = txt.replaceAll(...);
txt = txt.replaceAll(...); // split behavior
Files.write(Paths.get("out.txt"), txt.getBytes(StandardCharsets.UTF_8));

Added:
Though the logic escapes me, the replacements probably should be:
finale String EOL = "\n";
txt = txt.replaceAll("^.*?1002|1003(.(?!1002))*$", EOL ) // trim leading/trailing non-data
txt = txt.replaceAll("1003.*?1002", EOL ) // split on end-to-start-of-next

Comment: while writing the splitting condition it shows error
Comment: Added my understanding of what should be done in the replaceAlls. Maybe EOL should be "\r\n" if for Windows.
Answer: You could try that:
public static void main(String a[]) throws Exception
{
    try {
        PrintWriter os = new PrintWriter("output.txt");
        Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
            .replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
            .split("1003.*?1002"))                        // split on end-to-start-of-next
            .forEachOrdered(os::println);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

Answer: No sure what exactly are you looking for. Here is one way of doing it and what I would do.
You can do this directly from the terminal
javac myFile.java
java ClassName > myfile.txt

This would save your output into a file 'myfile.txt'
Comment: does not working through terminal..if u know from eclipse or netbeans plz tell


Functions on Euclidean Space; Real Analysis

Question: Undergraduate student here, taking real analysis.  I'm stuck on a question of proving that if $A$ is a bounded subset of $\mathbb{R}^{p}$ and $F: \mathbb{R}^p \longrightarrow \mathbb{R}^{d}$ is continuous then $F(\overline{A})$=$\overline{F(A)}$.
My attempt at a proof is given below.
We need to prove that $f(a) \in \overline{F(A)} \iff f(a) \in f(\overline{A})$.
For $\Rightarrow$: Assume $f(a) \in \overline{F(A)}$.  Then $a \in \overline{A}$.  If $a \in \overline{A}$, then we know that $f(a) \in f(\overline{A})$.
For $\Leftarrow$: Assume $f(a) \in f(\overline{A})$.  So $a \in \overline{A}$. if $a \in \overline{A}$, we know that $a \in \partial{A}$ or $a \in A^{\circ}$.  If $a \in \partial{A}$, then $f(a) \in \overline{f(A)}$, since $\partial{A} \subset \overline{A}$. Similarly, if  $a \in A^{\circ}$ then $f(a) \in \overline{f(A)}$.
I'm sure there are holes in the proof.  Like I said, I'm stuck and I need some help/pointers.
Comment: Why is that if $f(a) \in \overline{F(A)}$ then $a \in \overline{A}$?
Comment: You need to prove that $y \in ...$ **iff** $y \in ...$, not $f(a)$.
Comment: You need to use boundedness somewhere. Take $f(x) = e^{-|x|}$ and $A=\mathbb{R}$ to see why. Note that $F(A) \subset F(\overline{A})$, and so $\overline{F(A) } \subset F(\overline{A})$, when $A$ is bounded, since $\overline{A}$ is compact.
Comment: @copper.hat, isn't $y \in \mathbb{R}^q$ the same as $f(a)=y$?
Comment: Only if there is some $a$  in the relevant set so that $f(a) = y$.
Comment: Yes, but you might be better off trying a sequence approach and the fact that $A$ is bounded.
Comment: @copper.hat if $y \in \overline{F(A)}$, then we know that $y \in F(A)$ or $y \in \partial{F(A)}$, right?  So can't we say that if $y \in F(A)$, then $y \in F(\overline{A})$, since $F(A) \subset F(\overline{A})$?  And can't we make a similar statement about the case when $y \in \partial{A}$?
Comment: I'm not sure what you are trying to get at. You need to use the fact that $A$ is bounded.
Answer: Fill in the details of this argument:
To see that $\overline{F(A)}\subset F(\bar{A})$, note $\bar{A}$ is compact. So $F(\bar{A})$ is a compact, hence closed, subset of $\Bbb R^d$. As $F(\bar{A})$ is a closed set containing $F(A)$, $\overline{F(A)}\subset F(\bar{A})$.
To prove $F(\bar{A})\subset \overline{F(A)}$, take an arbitrary $z\in F(\bar{A})$. Then $z = F(u)$ for some $u\in \bar{A}$. There is a sequence $(a_n)$ in $A$ such that $\lim\limits_{n\to \infty} a_n = u$. Then $z = F(u) = \lim\limits_{n\to \infty} F(a_n) \in \overline{F(A)}$. Hence, $F(\bar{A})\subset \overline{F(A)}$.
Comment: Just out of curiosity, what would happen if $A \subseteq \mathbb{R}^{p}$? It seems like you can't assume that there is a sequence $(a_n)$, can you?
Comment: I don't see what you mean @Mr.F, since $A\subset \Bbb R^p$ already. Also, elements of $\bar{A}$ are limits of sequences in $A$, for if $u\in \bar{A}$, then for each $n$, there exists $a_n \in B_{1/n}(u)\cap A$. Thus $\|a_n -u\| < 1/n$ for all $n\in \Bbb N$, forcing $a_n \to u$.
Comment: If $A \subseteq \mathbb{R}^{p}$, then $A$ could potentially be the entire space $\mathbb{R}^{p}$, couldn't it?  If $A$ is unbounded, I'm having trouble seeing how we can say there's a convergent sequence.  Otherwise, I feel like I understand everything else.
Comment: @Mr.F if $A = \Bbb R^p$, then every $a\in \bar{A}$ is the limit of the constant sequence $\{a,a,a,\ldots\}$.
Comment: Oh, duh.  Now it makes sense.  Thanks so much, you've helped a ton.
Comment: @GeorgeOscarBluth could you please explain why you unchecked my answer?
Comment: Sorry, accidentally hit the uncheck button.


AngularJS: $eval takes much time

Question: During profiling of my angularjs application, I found that sometimes $get.Scope.$eval takes more than 100ms. During the single $digest loop there are at least 3 long cases of $get.Scope.$eval and I'd like to optimize this part.
Below the $get.Scope.$eval in profiler I see only invoking of angularjs code.
Here is a screenshot of profile chart.

Could anyone suggest, what's going on and how to optimize this part? I suppose that it can be caused by ng-repeat, ng-include or ng-if, but I'm not sure.
Update:
Here is the simplified structure of my application. Probably, the problem is in the architecture of my application. The app mostly working on the single route and change it only for 3 cases, so application store state in the global controller AppController - fat controller. Also there are 20k+ nodes in the html and the number can grow(maximum I saw is 60k)
Answer: $eval is used internally by angular when resolving angular expressions, such as {{variable}}. Without seeing any of your code, it's hard to tell what expressions are using resources unnecessarily, but usually too large or nested ng-repeats (or many ng- directives included within an ng-repeat) are a code smell.
Angular uses dirty checking to evaluate these expressions (for lack of a better option) - that means that every time you create a binding with the {{}} syntax, it creates an implicit $watch expression getting that value, that will be called every digest cycle to see if the value has changed (on which change the relevant parts of the DOM are regenerated).
Here's one optimization I've used successfully in the past:
most of the time, when you bind a value with {{}}, you don't actually expect the value to change (like a label), and this 2-way data binding is completely superflous. Since angular version 1.3 you have the options to create one-time bindings with the :: syntax:

One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value

which eliminates the corresponding performance overhead of such bindings. (If you're using older angular versions, external libraries can mimick this behaviour, such as bindonce.)
Here are some additional tools I've found useful while profiling/optimizing angular apps:

Batarang, a chrome extension "for debugging and profiling angular applications"
This stackoverflow answer, giving a neat solution for counting how many watch expressions are active on your page. A rule of thumb is that if you're above 2000, you'll start noticing performance issues, and you should think about changing your architecture - employ lazy loading mechanisms, reconsider whether you truly need all the bindings etc.
In production environments disabling the default "debug mode" of angular can also help with performance.
Comment: Thanks! Unfortunately I already use and and `::`, and batarang and trying to reduce a number of watchers. I have less then 2k of watchers and really slow application. Probably architecture that I use is wrong, but it's another question.
Comment: As for architecture, I have a lot of `ng-if`, `ng-show` and `ng-repeat` without the changing the route. And after every user's action all my 300+ scopes need to be digested. And probably `$eval` tries to evaluate a lot of my nested `ng-include`, but I don't know and trying to understand it with my question
Comment: 300+ active scopes sounds like a nightmare, both performance and maintainability-wise. Are you sure you need all of those at the same time? Can you give us some code samples of some more complicated nested structures?
Comment: sure, but it's probably a more common question that current one. I'll add sheme of code structure a little bit later
Comment: Here is simplified structure of the code https://gist.github.com/havenchyk/c1c668de6bc112ea93f2#file-code-md

I change route only for 3 cases, so mostly application store state in the global controller `AppCtrl`
Comment: You should edit these comments into your original question, so people can see them and respond properly.

AngularJS: $eval takes much time


JavaFX: Combo box focus issue in table view

Question: Scenario: I have created a table view in JavaFx with 2 columns. I have populated the table with some sample data. Now, I have to edit the cells of my table. For that I created a new class (ComboTableCell) which overrides the TableCell class. This class defines the cell-factory of an editable combo-box which works perfectly if I use mouse clicks to traverse through the table. However, when i use keyboard tab totraverse, i face an issue.
Problem: When the first cell is selected using tab, the combo-box and its editor gets the focus. Hence user can directly start editing the cell.
The problem is that when I am done editing the first cell, I move to the next cell using the TAB button, however, the combo-box in the next cell does not get the focus and hence the user cannot directly start typing as in the case of first cell. Even the table does cell does not get the focus.
I have tried using the below code to get focus back to combo-box when I press tab
Platform.runLater(new Runnable() {
        @Override
        public void run() {
            comboBox.requestFocus();

            //I have also tried with comboBox.getEditor().requestFocus(); but still the issue persists
            comboBox.getEditor().selectAll();
        }
    });

Pls help me out with this issue.
Answer: I have to face the same issue and i just found an workaround. If you make it as editable combo, it will resolve your issue.
ComboBox cb = new ComboBox();
cb.setEditable(true);


python 3 and tensorflow on AWS EMR

Question: For EMR AWS has tensorflow 1.9 as part of the software stack for release 5.17. I have my own bootstrap script to install python 3.6 and tensorflow 1.9, I took out the tensorflow installation - but it didn't work -- I get on the master node, run python3, I get into my new python 3.6 but there is no tensorflow in my installation. I must have installed a new python, I guess my question is how do I use the native python3 installation with tensorflow on AWS EMR, with spark - and am I lucky enough for that python3 to by 3.6?
This is my bootstrap script:
#!/usr/bin/env bash

sudo yum -y upgrade
sudo yum -y install git autoconf automake libevent-devel python36.x86_64 python36-pip.noarch python36-devel.x86_64

sudo python36 -m pip install --upgrade pip

sudo python36 -m pip install --upgrade wheel cython

sudo python36 -m pip install py4j jupyter ipython pandas scipy pyyaml scikit-learn ipykernel matplotlib seaborn h5py configobj ujson

echo -e "\n\n" >> ~/.bashrc
echo 'export PYSPARK_PYTHON=/usr/bin/python36' >> ~/.bashrc

I guess I'll try it without a bootstrap script, maybe it will just work?
Answer: From AWS:

Amazon EMR release versions 4.6.0-5.19.0: Python 3.4 is installed on the cluster instances. Python 2.7 is the system default.
Amazon EMR release versions 5.20.0 and later: Python 3.6 is installed on the cluster instances. Python 2.7 is the system default.

You can install python3.6 using the following bootstrap action. Also, I recommend using virtualenv to run your python scripts and keeping the required libraries info on s3 using requirements.txt file.
#!/bin/bash -xe
sudo yum install -y python36 python36-devel postgresql-devel unixODBC-devel # For pyodbc, psycopg2
virtualenv --system-site-packages /home/hadoop/workspace -p /usr/bin/python3.6 # Install virualenv
source /home/hadoop/workspace/bin/activate
aws s3 cp s3://<bucket>/requirements.txt /home/hadoop/ # Keep your required pip freeze info (tensorflow, etc...) on s3
pip install -r /home/hadoop/requirements.txt # Install your packages
# Run your scripts during main execcution using /home/hadoop/workspace/bin/python3

Answer: It looks like right now (sept 2018) AWS EMR is at python 3.4. Without a bootstrap script, I can run python3 and get their tensorflow.
Comment: How? Just spun up and everything is wrong python. Nothing works basically. Used defaults.
Comment: Did you check the tensorflow box when you made the cluster? I haven't done this for a while, but it might not be enough to just select the 5.17 software release, you may need to be in advanced and select tensorflow.

python 3 and tensorflow on AWS EMR


Array of html entities "" how to print? as unicode (not working)?

Question: I have an array of HTML entities (custom font) that looks like this:
const arr = [''];

Now when I print it out like this:
render() {
   return (

          { arr[0] }

   )
}

It prints the string. I am trying to convert it to unicode like this:
{ arr[0].replace('&#', '\\u') }

But then this just prints the string "\uxf100".
I was having to do this to get it to work:
{ React.createElement('span', { dangerouslySetInnerHTML:{ __html:arr[0] }}, null) }

Answer: String.fromCodePoint(parseInt(arr[0].replace(/&#x|;/g,''),16))
//

Try this first we replace '&#x' and ';' with '', then with parseInt() we convert it from hexadecimal to decimal, then with String.fromCodePoint() we convert the decimal code point into a Javascript string.
Comment: Ah that's interesting, perhaps the codepoint identifier site misidentified the code point. I'll edit the question.
Comment: This works thanks Steven! However I had to remove the ` - 1`.


Views UI broken after site migration

Question: Ive migrated my site and now my View UI is broken. My relationship 'Relationship: Entity Reference: Referencing entity' works the opposite way round to the way it should. This has been confirmed by a colleague who uses Drupal.
Also fields that ive added to my content type are not available as fields in views, and sometimes the body field is missing too.
Does anyone have any ideas as to how I would start to go about fixing this? My Drupal status report doesn't return any errors.
Comment: Looks like you simply encountered a bug in module. Never happened to me, I don't believe anyone will be able to help you, unless you provide more info about migration process - and then it will be helpful only for you, so it's place is in views' issue queue or paid support request, I'm afraid.
Comment: I'm afraid I have to agree with @Mołot. There's nothing in the post to indicate what's gone wrong, nor does the error you're seeing make any sense to me. Either we'd need to dissect the migration process, or do site specific in-depth debugging, which is off-topic here.
Answer: Disabling a custom module has fixed this.
Comment: Thank you for letting us know where the problem originated, but it would be nice if you could be a little more specific about the cause.
Comment: Ive disabled a bunch of modules that I didnt create and the developer who did make them wont be back in the office for a while. Ill post if and when I find out more.

Views UI broken after site migration


Possivel redirecionar função sem rota no Laravel?

Question: Estou utilizando uma funcionalidade para gerar relatorios em PDF utilizando Laravel. Porém estou em duvida se é possivel a partir de um simples botão de HTML, poder redirecionar automaticamente para uma função do meu controller sem ter que criar uma nova rota. Eu gostaria como exemplo colocar a função e transformar em um objeto para assim ser chamada na view como mostrado abaixo.
Gerar PDF

Como aconteceria no JavaScript. A função que desejo redirecionar é essa:
function generatePDF(){
            $pdf = PDF::loadView('dashboard-pdf',$dados)->setPaper('a4', 'landscape');
            return $pdf->stream();
        }

Seria possivel fazer algo parecido com o Laravel ou teria mesmo que criar uma nova rota só para realizar essa função?
Answer: O que pode ser feito é você criar uma pasta de Helpers no seu app, criar um arquivo com sua função e carrega-la através do composer, inserindo em composer.json, em "autoload" (conforme exemplo):
"autoload": {
    "psr-4": {
        "Intranet\\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "files": [
        "app/Helpers/ArquivoComFuncoes.php"
    ]

Dessa forma sua função ficará disponível para toda a aplicação.
Entretanto, não vejo motivos para não fazer uso das rotas (o que está dentro das boas práticas).
Comment: É que eu possuo um código grande para adicionar os valores corretos em $dados. E daí pensei em alguma forma de reduzir um pouco essa quantidade de código. Mas se fazer isso equivale a praticas ruins. Pretenderei criar rotas normais mesmo.


Jmeter EVENTVALIDATION and VIEWSTATE values passed incorrectly

Question: I need to login a webpage. Passing the parameters from navigation screen,to POST to login screen i used CSS/Jquery extractor. of the three values extracted, Viewstate generator value is passed correctly. But Eventvalidation and Viewstate has completely different values when passed.
Values i get from Navigating to the website:
`VIEWSTATEGENERATORExtractor=C2EE9ACC,VIEWSTATEExtractor=r6PHK0,
EVENTVALIDATIONExtractor=xLhYcNpU3vb8+Om5`
And passed as VIEWSTATEGENERATOR =C2EE9ACC
EVENTVALIDATION value=Blncm,VIEWSTATE" value=iFpefxx7

Some values are generated when passed through but not from previous browser navigation.
DO not understand how 1 value can be passed correctly and not other two. I use same format for all the three
Comment: share the full response and regex expression. There is a chance that there are more than 1 viewstate
Comment: I used CSS/Jquery Extractor with Jsoup:Jquery expression as input[id=__viewstate],Attribute as Value;Match No:1 . When passed as parameter the result i get is  <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="V7gWhPIG" This value is different from what i get in previous request.
Comment: I am struck because some random values are passed between the requests though i use {eventvalidation} reference. It does not pass incorrect values but some random values between the requests and
Answer: This is the whole point of viewstate and eventvalidation parameters, they are different each time, that's why you need to correlate them for each request.VIEWSTATE has all the information about client-side page state, basically what did the user do on each step. EVENTVALIDATION is a form of CSRF protection, so it has to be different each time as well.
You can validate that your script is doing what it is supposed to be doing using View Results Tree listener.
References:

Page.EnableEventValidation Property
ASP.NET View State Overview
ASP.NET Login Testing with JMeter
Comment: Thanks so much Dmitri. But one more clarification So why do we have to pass the Event validation and viewstate as parameters from one step to another?                                       http://stackoverflow.com/questions/33030823/could-not-handle-view-state-and-event-validation-in-jmeter-load-testing


The Supremum and Infimum of a sequence of measurable functions is measurable

Question: I am reading through Folland's Real Analysis: Modern Techniques and Their Applications, and they have the following proposition and proof:

Proposition: If $\{f_{j}\}$ is a sequence of $\bar{\mathbb{R}}$- valued measurable functions on $(X, \mathcal{M})$, then the functions:
$$g_{1}(x)=\sup_{j} f_{j}(x)$$ $$g_{2}(x)=\inf_{j} f_{j}(x)$$ are
  measurable.
Proof:
We have
$$g_{1}^{-1}((a,\infty])= \bigcup_{j=1}^{\infty}
 f_{j}^{-1}((a,\infty])$$ $$g_{2}^{-1}([-\infty,a))=
 \bigcup_{j=1}^{\infty} f_{j}^{-1}([-\infty,a))$$
Where the result follows from the fact that $g_{1}^{-1}((a,\infty])\in
 \mathcal{M}$ for all $a \in \mathbb{R} \iff g$ is measurable, and
  $g_{2}^{-1}([-\infty,a))\in \mathcal{M}$ for all $a \in \mathbb{R}
 \iff g$ is measurable.

I understand the last part of the proof, but how do we know $g_{1}^{-1}((a,\infty])= \bigcup_{j=1}^{\infty}f_{j}^{-1}((a,\infty])$ and $g_{2}^{-1}([-\infty,a))=\bigcup_{j=1}^{\infty} f_{j}^{-1}([-\infty,a))$? I would appreciate any help with this.
Answer: This is the same as Augustin's answer, but to make it psychologically "more tautological"...
Think of unions as 'there exists' [and intersections as 'for all'].
Writing $\{\, P\, \}$ for $\{x\, | P(x) \}$ below:
For instance, in your case,
$$ \{\, \def\S {\sup_k\ f_k} \S >a\, \} = \bigcup_k\ \{\, f_k > a\, \} $$
is the statement that if $\S(x)>a$, then there exists a $k$ such that $f_k (x) >a$, and conversely:  if there exists a $k$ such that $f_k (x) > a$, then ...
Likewise, (not what you are asking, but here for illustration)
$$
\{\, \inf_k f_k\ge a\, \} = \bigcap_k\ \{\, f_k \ge a \,\}$$
is the statement
that  $\inf_k f_k(x) \ge a $ if and only if $f_k(x) \ge a$ for all $k$.
Comment: This answer (tautological, though it may be) is in memory of Carl Herz.
Answer: Hint: $\sup_j f_j(x)\gt a\iff \exists j,\, f_j(x)\gt a$.