Commit do trabalho original em C.

Commit do trabalho original em C.

error: pathspec 'Tr1-PedroTorres-160141575.c' did not match any file(s) known to git

--- Tr1-PedroTorres-160141575.c
+++ Tr1-PedroTorres-160141575.c
@@ -0,0 +1,607 @@
+/* Programa Batalha Náutica
+ *
+ * Este programa simula o jogo Batalha Naval, com um tabuleiro de tamanho variável e a opção de preenchê-lo automaticamente, de forma aleatória.
+ *
+ * Aluno: Pedro Lucas S. H. Torres
+ * Matrícula: 16/0141575
+ * Matéria: Estrutura de Dados, turma B
+ * Data de criação do código: 02/04/2017
+ * Editado em: 05/04/17, 06/04/17, 07/04/17;
+ *
+*/
+
+/* ---Bibliotecas--- */
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <ctype.h>
+
+/* ---Estruturas--- */
+struct Navio{
+    char classe[17];    /* Nome da embarcacao */
+    char desig;         /* Primeira letra (exceto no caso do contratorpedeiro) que sera impressa no tabuleiro */
+    int qtd;            /* Numero de embarcacoes disponiveis para posicionar */
+    int tam;            /* Quantidade de embarcacoes da classe disponiveis */
+};
+
+struct Navio Embarc[] = {           /* Atribuicao dos valores para a estrutura */
+    {"Porta-avioes", 'P', 1, 5},
+    {"Encouracado", 'E', 2, 4},
+    {"Cruzador", 'C', 3, 3},
+    {"Submarino", 'S', 4, 3},
+    {"Contratorpedeiro", 'T', 5, 2}
+};                                  /* Fim da atribuicao */
+
+/* ---Funcoes--- */
+int teste       (int var, int isso, int aquilo, int tipo);                                          /* Testa a validade da entrada do usuario de acordo com os parametros passados para a funcao */
+void batalha    (void);                                                                                /* Executa o jogo */
+void almirante  (int colunas, int linhas, int ***player);                                                       /* Permite o jogador posicionar suas embarcacoes no tabuleiro manualmente */
+void marinheiro (int colunas, int linhas, int ***player);                                                       /* Posiciona as embarcacoes do jogador aleatoriamente */
+int brief1      (int ***player1, int ***player2, int *lastx, int *lasty, int *pontlife, int linhas, int colunas, int lifepl);  /* Roda o jogo do player 1 */
+int brief2      (int ***player1, int ***player2, int *lastx, int *lasty, int *pontlife, int linhas, int colunas, int lifepl);  /* Roda o jogo do player 2 */
+
+int main(void) {    /* Funcao principal */
+    int continuar;  /* Recebe uma entrada do usuario, relativa ao desejo de jogar */
+
+    printf("\nBem vindo ao programa Batalha Nautica!\nEste programa simula o jogo Batalha Naval, com um tabuleiro de tamanho definido\npor voce e a opcao de preenche-lo automaticamente.\n");   /* Mensagem de boas vindas */
+    printf("Deseja jogar? (Sim: 1 | Nao: 0)\n");    /* Pergunta se o usuario deseja jogar o jogo */
+    scanf("%i", &continuar);
+
+    continuar = teste(continuar, 1, 0, 1);          /* Testa a validade da entrada do usuario */
+
+    while (continuar == 1) {    /* Laco que executa o jogo enquanto o usuario desejar */
+        batalha();                                              /* Executa a funcao do jogo */
+
+        printf("Deseja jogar novamente? (Sim: 1 | Nao: 0)\n");  /* Pergunta se o jogador deseja jogar novamente, apos o fim da partida */
+        scanf("%i", &continuar);
+
+        continuar = teste(continuar, 1, 0, 1);                  /* Testa a validade da entrada do usuario */
+
+        if (continuar == 0) {                                   /* Caso o usuario nao queira mais jogar */
+            printf("\nObrigado por jogar e volte sempre!\n\n"); /* Imprime uma mensagem de agradecimento e termina o programa */
+            return(0); }
+    }
+
+    printf("Obrigado por usar o programa!\n");  /* Mensagem de agradecimento, caso o jogador decida nao jogar */
+
+return(0); }        /* -----Fim da funcao principal----- */
+
+int teste (int var, int isso, int aquilo, int tipo) {   /* Testa a validade da entrada do usuario (var) de acordo com os parametros passados para a funcao ('isso' e 'aquilo'), permitindo correcao. E retorna o valor da variavel para a funcao */
+
+    if (tipo == 1) {    /* TIPO 1: teste para sim (1) ou nao (0). */
+        while (var != isso && var != aquilo) {  /* Enquanto a entrada for diferente de 0 e 1, repete, permitindo correcao. */
+            printf("Sua entrada %i eh invalida. Digite um valor entre %i e %i\n", var, isso, aquilo);
+            scanf("%i", &var); }
+    }
+
+    else if (tipo == 2) {   /* TIPO 2: Faz comparacoes de maior que 'isso', menor que 'aquilo'. */
+        while (var < isso || var > aquilo) {    /* Enquanto a entrada nao possuir os valores aceitos repete, permitindo a correcao. */
+            printf("Sua entrada %i eh invalida. Digite um valor entre %i e %i\n", var, isso, aquilo);
+            scanf("%i", &var); }
+    }
+
+return(var); }  /* -----Fim da funcao teste----- */
+
+void batalha (void) {   /* Funcao batalha: executa todos os passos do jogo */
+
+    int linhas, colunas, bool, i, j;                                                        /* Variaveis que receberao valores e nao precisam ser inicializadas */
+    int lifepl1 = 0, lifepl2, lastx[2] = {0, 0}, lasty[2] = {0, 0};                         /* Variaveis e vetores que precisam ser inicializadas */
+    int *pontx1 = &lastx[0], *pontx2 = &lastx[1], *ponty1 = &lasty[0], *ponty2 = &lasty[1]; /* Ponteiros para os vetores */
+    int *pontlife1 = &lifepl1, *pontlife2 = &lifepl2;                                       /* Ponteiros para a vida dos jogadores */
+
+    printf("Quantas linhas voce deseja em seu tabuleiro? (Min: 10 | Max: 16)\n");   /* Pergunta e recebe a quantidade de linhas do tabuleiro de acordo com os criterios descritos */
+    scanf("%i", &linhas);
+
+    linhas = teste(linhas, 10, 16, 2);  /* Testa a validade da entrada do usuario */
+
+    printf("Quantas colunas voce deseja em seu tabuleiro? (Min: 10 | Max: 16)\n");  /* Pergunta e recebe a quantidade de colunas do tabuleiro de acordo com os criterios descritos */
+    scanf("%i", &colunas);
+
+    colunas = teste(colunas, 10, 16, 2);    /* Testa a validade da entrada do usuario */
+
+    int ***player1 = (int***) malloc(linhas*(sizeof(int**)));   /* Alocacao de memoria para os tabuleiros dos jogadores */
+
+    for (i = 0; i < colunas; i++) {
+        player1[i] = (int**) malloc(colunas*(sizeof(int**)));
+        for (j = 0; j < linhas; j++)
+            player1[i][j] = (int*) malloc(3*(sizeof(int*)));
+    }
+
+    int ***player2 = (int***) malloc(linhas*(sizeof(int**)));
+
+    for (i = 0; i < colunas; i++) {
+        player2[i] = (int**) malloc(colunas*(sizeof(int**)));
+
+        for (j = 0; j < linhas; j++)
+            player2[i][j] = (int*) malloc(3*(sizeof(int*)));
+    }                                                           /* Fim do processo de alocacao de memoria */
+
+
+    printf("Player 1, deseja posicionar suas embarcacoes aleatoriamente? (Sim: 1 | Nao: 0)\n"); /* Questiona se o jogador 1 deseja posicionar suas embarcacoes aleatoriamente e recebe sua entrada*/
+    scanf("%i", &bool);
+
+    bool = teste(bool, 1, 0, 1);    /* Testa a validade da entrada do usuario */
+
+    srand(time(NULL));  /* Inicializa uma seed para a funcao rand() que sera utilizada caso um dos jogadores deseje posicionar suas embarcacoes aleatoriamente */
+
+    if (bool == 0)      /* Caso bool == 0, chama a funcao que permite o jogador 1 posicionar suas embarcacoes manualmente no tabuleiro */
+        almirante(colunas, linhas, player1);
+    else                /* Caso contrario, chama a funcao que posiciona as embarcacoes aleatoriamente */
+        marinheiro(colunas, linhas, player1);
+
+    printf("Player 2, deseja posicionar suas embarcacoes aleatoriamente? (Sim: 1 | Nao: 0)\n"); /* Questiona se o jogador 2 deseja posicionar suas embarcacoes aleatoriamente e recebe sua entrada*/
+    scanf("%i", &bool);
+
+    bool = teste(bool, 1, 0, 1);    /* Testa a validade da entrada do usuario */
+
+    if (bool == 0)      /* Caso bool == 0, chama a funcao que permite o jogador 1 posicionar suas embarcacoes manualmente no tabuleiro */
+        almirante(colunas, linhas, player2);
+    else                /* Caso contrario, chama a funcao que posiciona as embarcacoes aleatoriamente */
+        marinheiro(colunas, linhas, player2);
+
+    for (i = 0; i < 5; i++) /* Inicializa a vida dos jogadores (lifepl1 e 2) que servira de criterio de parada para o jogo */
+        lifepl1 = lifepl1 + (Embarc[i].tam * Embarc[i].qtd);
+
+    lifepl2 = lifepl1;      /* Fim da inicializacao das vidas */
+
+    bool = 0;   /* Define a variavel bool = 0 para garantir a entrada no laco a seguir */
+
+    while (bool != 1) { /* Laco para evitar que um jogador veja o tabuleiro do outro */
+        printf("Voce eh o player 1? (Sim: 1| Nao: 0)\n");
+        scanf("%i", &bool);
+
+        teste(bool, 0, 1, 1); } /* Testa a validade da entrada do usuario */
+
+    while (lifepl1 > 0 && lifepl2 > 0) {                                                /* Laco que roda o jogo, em si */
+        lifepl2 = brief1(player1, player2, pontx1, ponty1, pontlife1, linhas, colunas, lifepl2);   /* Chama a funcao brief1 para que o jogador 1 faca sua jogada */
+
+        if (lifepl2 == 0)                                                               /* Teste para evitar que o jogador 2 jogue uma rodada com todas suas embarcacoes afundadas */
+            break;
+
+        bool = 0;                                                                       /* Define a variavel bool = 0 para garantir a entrada no laco a seguir */
+
+        while (bool != 1) {                                                             /* Laco para evitar que um jogador veja o tabuleiro do outro */
+            printf("Voce eh o player 2? (Sim: 1| Nao: 0)\n");
+            scanf("%i", &bool);
+
+            teste(bool, 0, 1, 1); }                                                     /* Testa a validade da entrada do usuario */
+
+        for(i = 1; i < 120; i++)                                                        /* Abre um espaco para garantir que um jogador nao veja o tabuleiro do outro */
+            printf("\n");
+
+        lifepl1 = brief2(player1, player2, pontx2, ponty2, pontlife2, linhas, colunas, lifepl1);   /* Chama a funcao brief1 para que o jogador 2 faca sua jogada */
+
+        bool = 0;                                                                       /* Define a variavel bool = 0 para garantir a entrada no laco a seguir */
+
+        while (bool != 1) {
+            printf("Voce eh o player 1? (Sim: 1| Nao: 0)\n");                           /* Laco para evitar que um jogador veja o tabuleiro do outro */
+            scanf("%i", &bool);
+            teste(bool, 0, 1, 1); }                                                     /* Testa a validade da entrada do usuario */
+
+        for(i = 1; i < 120; i++)                                                        /* Abre um espaco para garantir que um jogador nao veja o tabuleiro do outro */
+            printf("\n");
+
+    }
+
+    free(player1);  /* Processo para liberar a memoria alocada */
+    free(player2);
+
+    for (i = 0; i < colunas; i++) {
+        for (j = 0; j < linhas; j++) {
+            free(player1[i][j]);
+            free(player2[i][j]); }
+
+        free(player1[i]);
+        free(player2[i]);
+    }               /* Fim do processo de liberacao de memoria */
+
+    if (lifepl1 > lifepl2)                                  /* Testa qual jogador venceu e imprime uma mensagem de vitoria */
+        printf("\n\nParabens Player 1! Voce venceu!\n");
+    else
+        printf("\n\nParabens Player 2! Voce venceu!\n");
+
+} /* -----Fim da funcao batalha----- */
+
+void almirante (int colunas, int linhas, int ***player) {   /* Funcao almirante: Permite que o jogador posicione suas embarcacoes manualmente */
+
+    int i, j, k, direcao, qtd, x, y;    /* i, j, k sao variaveis de contagem; 'direcao' recebe valores 0 (horizontal) ou 1 (vertical); 'qtd' recebe a quantidade de cada uma das embarcacoes; x, y recebe a entrada de coluna e linha, respectivamente */
+    int flag = 1;                       /* flag para uma serie de testes de validez */
+
+    for (i = 0; i < colunas; i++)       /* Inicializa o tabuleiro */
+        for (j = 0; j < linhas; j++) {
+            player[j][i][0] = '~';
+            player[j][i][1] = 0;
+        }                               /* Fim da inicializacao do tabuleiro */
+
+    i = 0;                  /* Reinicializa a variavel de contagem para o laco a seguir */
+    qtd = Embarc[i].qtd;    /* Inicializa a variavel com o valor da quantidade de porta-avioes */
+
+    while (i < 5) {         /* Inicializa o laco para posicionar cada uma das embarcacoes */
+        printf("  ");                       /* Impressao do tabuleiro */
+
+        for (j = 1; j <= colunas; j++)
+            printf("|%2i", j);
+        printf("|\n");
+
+        for (j = 0; j < linhas; j++) {
+            printf("%2i", j+1);
+
+            for (k = 0; k < colunas; k++)
+                printf("|%2c", player[k][j][0]);
+
+            printf("|\n");
+        }                                   /* Fim da impressao do tabuleiro */
+
+        printf("\nDeseja posicionar seu %s na horizontal (0) ou vertical (1)? ", Embarc[i].classe); /* Pergunta e recebe a direcao de posicionamento da embarcacao em questao */
+        scanf("%i", &direcao);
+
+        teste(direcao, 0, 1, 1);    /* Testa a validade da entrada do usuario */
+
+        printf("O %s ocupa %i quadrantes. Em quais coordenadas voce deseja\nposiciona-lo? (O navio sera posicionado nas coordenadas desejadas e ocupara as\ncoordenadas subsequentes de ", Embarc[i].classe, Embarc[i].tam);
+        printf("acordo com a sua escolha de direcao)\n");   /* Imprime intrucoes relativas ao posicionamento da embarcacao */
+
+        while (flag != 0) {
+            printf("Em qual linha deseja posicionar sua embarcacao? ");     /* Pergunta e recebe a linha onde a embarcacao sera posicionada */
+            scanf("%i", &y);
+            printf("Em qual coluna deseja posicionar sua embarcacao? ");    /* Pergunta e recebe a coluna onde a embarcacao sera posicionada */
+            scanf("%i", &x);
+
+            teste(y, 1, linhas, 2);         /* Verifica a validez da variavel y */
+
+            teste(x, 1, colunas, 2);        /* Verifica a validez da variavel x */
+
+            x = x-1;    /* Ajustes para adequar a matriz */
+            y = y-1;
+            flag = 1;   /* Levanta a flag caso ela tenha sido mudada numa iteracao anterior */
+
+            if (direcao == 0) {                     /* Caso a direcao seja horizontal */
+                if (x+Embarc[i].tam > colunas) {    /* Testa se a embarcacao ficaria parcialmente fora do tabuleiro ao ser posicionada */
+                    printf("Sua entrada eh invalida, porque parte de seu navio ficaria fora do tabuleiro.\nEscolha outras coordenadas para ele. (Os mesmos criterios se aplicam.)\n");
+                    flag = 2; }
+                else {                              /* Testa se a embarcacao ficaria em um espaco ja ocupado por outra e evita chamar uma regiao da memoria nao alocada */
+                    for(j = x; j < x+Embarc[i].tam; j++)
+                        if (player[j][y][0] != '~') {
+                            printf("Sua entrada eh invalida, porque seu navio ficaria numa posicao ja ocupada por\noutro. Escolha outras coordenadas para ele. (Os mesmos criterios se aplicam.)\n");
+                            flag = 2;
+                            break; }
+                }
+
+                if (flag != 2) {    /* Caso a flag nao tenha sido levantada pelos testes anteriores */
+                    flag = 0;       /* Define a flag como 0 para sair do laco */
+
+                    for(j = x; j < x+Embarc[i].tam; j++) {  /* Posiciona a embarcacao de acordo com o desejado */
+                        player[j][y][0] = Embarc[i].desig;
+                        player[j][y][2] = direcao;
+                    }
+
+                    qtd--;          /* Diminui em uma unidade o numero de embarcacoes */
+                }                   /* Fim do posicionamento da embarcacao */
+            }
+            else {                                  /* Caso a direcao seja vertical */
+                if (y+Embarc[i].tam > linhas) {     /* Testa se a embarcacao ficaria parcialmente fora do tabuleiro ao ser posicionada */
+                    printf("Sua entrada eh invalida, porque seu navio ficaria fora do tabuleiro. Escolha\noutras coordenadas para ele. (Os mesmos criterios se aplicam.)\n");
+                    flag = 2; }
+                else {                              /* Testa se a embarcacao ficaria em um espaco ja ocupado por outra e evita chamar uma regiao da memoria nao alocada */
+                    for(j = y; j < y+Embarc[i].tam; j++)
+                        if (player[x][j][0] != '~') {
+                            printf("Sua entrada eh invalida, porque seu navio ficaria numa posicao ja ocupada por\noutro. Escolha outras coordenadas para ele. (Os mesmos criterios se aplicam.)\n");
+                            flag = 2;
+                            break; }
+                }
+
+                if (flag != 2) {    /* Caso a flag nao tenha sido levantada pelos testes anteriores */
+                    flag = 0;       /* Define a flag como 0 para sair do laco */
+
+                    for(j = y; j < y+Embarc[i].tam; j++)    /* Posiciona a embarcacao de acordo com o desejado */
+                        player[x][j][0] = Embarc[i].desig;
+
+                    qtd--;          /* Diminui em uma unidade o numero de embarcacoes */
+                }                   /* Fim do posicionamento da embarcacao */
+            }
+        }
+    flag = 1;       /* Reseta a flag */
+    if (qtd == 0) {             /* Caso a quantidade de embarcacoes chegue a zero */
+        i++;                    /* Acrescenta uma unidade ao contador */
+        qtd = Embarc[i].qtd; }  /* Muda a quantidade de acordo com a classe da embarcacao */
+    }
+
+    for(i = 1; i < 120; i++)    /* Abre um espaco para garantir que um jogador nao veja o tabuleiro do outro */
+        printf("\n");
+
+}   /* -----Fim da funcao almirante----- */
+
+void marinheiro (int colunas, int linhas, int ***player) {  /* Funcao marinheiro: posiciona as embarcacoes de forma aleatoria no tabuleiro */
+
+    int i, j, x, y, qtd;    /* i, j sao variaveis de contagem; x, y recebem as coordenadas de linhas e colunas; qtd recebe a quantidade numerica de cada embarcacao */
+    int  flag = 0;          /* flag eh utilizada nos testes de poscionamento */
+
+    for (i = 0; i < colunas; i++)       /* Inicializa o tabuleiro */
+        for (j = 0; j < linhas; j++) {
+            player[j][i][0] = '~';
+            player[j][i][1] = 0;
+        }                               /* Fim da incializacao do tabuleiro */
+
+    i = 0;                  /* Define a variavel i como 0 para o laco a seguir */
+    qtd = Embarc[i].qtd;    /* Define a variavel qtd como a quantidade de porta-avioes */
+
+    while (i < 5) {     /* Inicia o laco para posicionar cada uma das embarcacoes */
+
+        x = rand() % colunas;   /* Define a variavel x de acordo com o numero de colunas */
+        y = rand() % linhas;    /* Define a variavel y de acordo com o numero de linhas */
+        flag = 0;
+
+        if ((x%2) == 0)         /* Caso x seja par, a embarcacao sera posicionada na horizontal */
+            if(x + Embarc[i].tam < colunas) {           /* Testa se a embarcacao ficaria parcialmente fora do tabuleiro ao ser posicionada e evita chamar uma regiao da memoria nao alocada */
+                for(j = x; j < x+Embarc[i].tam; j++)    /* Testa se a embarcacao ficaria em um espaco ja ocupado por outra */
+                        if (player[j][y][0] != '~')
+                            flag = 1;                   /* Levanta a flag caso a embarcacao fique em um espaco ja ocupado por outra */
+
+                if (flag == 0) {                            /* Caso a flag nao tenha sido levantada pelo teste anterior, posiciona a embarcacao utilizando o laco for */
+                    for(j = x; j < x+Embarc[i].tam; j++)
+                        player[j][y][0] = Embarc[i].desig;
+                    qtd--;                                  /* Reduz em uma unidade a variavel qtd */
+                }                                           /* Fim do posicionamento da embarcacao em questao */
+            }                                           /* Fim do primeiro teste de posicionamento */
+
+        else                    /* Caso x seja impar, a embarcacao sera posicionada na vertical */
+            if(y + Embarc[i].tam < linhas) {            /* Testa se a embarcacao ficaria parcialmente fora do tabuleiro ao ser posicionada e evita chamar uma regiao da memoria nao alocada */
+                for(j = y; j < y+Embarc[i].tam; j++)    /* Testa se a embarcacao ficaria em um espaco ja ocupado por outra */
+                        if (player[x][j][0] != '~')
+                            flag = 1;                   /* Levanta a flag caso a embarcacao fique em um espaco ja ocupado por outra */
+
+                if (flag == 0) {                            /* Caso a flag nao tenha sido levantada pelo teste anterior, posiciona a embarcacao utilizando o laco for */
+                    for(j = y; j < y+Embarc[i].tam; j++)
+                        player[x][j][0] = Embarc[i].desig;
+
+                    qtd--;                                  /* Reduz em uma unidade a variavel qtd */
+                }                                           /* Fim do posicionamento da embarcacao em questao */
+            }                                           /* Fim do primeiro teste de posicionamento */
+
+        if (qtd == 0) {             /* Caso a quantidade de embarcacoes chegue a zero */
+            i++;                    /* Acrescenta uma unidade ao contador */
+            qtd = Embarc[i].qtd; }  /* Muda a quantidade de acordo com a classe da embarcacao */
+    }                   /* Fim do laco para posicionar as embarcacoes */
+
+}   /* -----Fim da funcao marinheiro----- */
+
+int brief1 (int ***player1, int ***player2, int *lastx, int *lasty, int *pontlife, int linhas, int colunas, int lifepl) {  /* Funcao brief1: Executa o jogo em si para o jogador 1 */
+
+    int i, j;       /* Variaveis de contagem */
+    int bool = 0;   /* Variavel para evitar que um jogador veja o tabuleiro do outro */
+
+    while (bool != 1) { /* Laco para evitar que um jogador veja o tabuleiro do outro */
+        printf("Mesmo? (Sim: 1| Nao: 0)\n");
+        scanf("%i", &bool);
+
+        teste(bool, 0, 1, 1); } /* Fim do laco com um teste da validade da entrada do usuario */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador 1*/
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player1[j][k][0] != '~' && player1[j][k][1] == 1)   /* Caso o quadrante em questao possua uma embarcacao e ja tenha sido atirado, imprime o caractere '*' */
+                printf("| *");
+            else                                                    /* Caso contrario, imprime a propria designacao */
+            printf("|%2c", player1[j][k][0]); }
+
+        if (j == 1)
+            printf("|\t Ultima jogada (L): %2i\n", *lasty+1);   /* Imprime a ultima jogada do player ao lado de seu tabuleiro */
+
+        else if (j == 2)
+            printf("|\t Ultima jogada (C): %2i\n", *lastx+1);   /* Imprime a ultima jogada do player ao lado de seu tabuleiro */
+
+        else if (j == 3)
+            printf("|\t Seu life: %2i\n", *pontlife);       /* Imprime o life do player ao lado de seu tabuleiro */
+
+        else if (j == 4)
+            printf("|\t Life do adversario: %2i\n", lifepl);/* Imprime o life do adversario ao lado do tabuleiro  do player*/
+
+        else                                                /* Imprime o caractere '|' e a quebra de linha nas linhas seguintes */
+            printf("|\n");
+    }                                           /* Fim da impressao */
+    printf("\nSeu tabuleiro eh o de cima\n\n"); /* Impressao de uma pequena informacao pertinente */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador adversario*/
+
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player2[j][k][1] == 0)  /* Caso o jogador nao tenha atirado no quadrante em questao, ele vera um caractere '?' */
+                printf("| ?");
+            else                        /* Caso contrario, ele vera o elemento guardado no quadrante em questao */
+                printf("|%2c", player2[j][k][0]);
+        }
+        printf("|\n");
+    }                                   /* Fim da impressao do tabuleiro do jogador adversario */
+
+    printf("\n Proxima jogada: (linha)\t");     /* Pergunta e recebe a proxima linha a ser atirada */
+    scanf("%i", lasty);
+
+    printf("\n Proxima jogada: (coluna)\t");    /* Pergunta e recebe a proxima coluna a ser atirada */
+    scanf("%i", lastx);
+
+        teste(*lasty, 1, linhas, 2);    /* Testa a validade da entrada do usuario */
+        teste(*lastx, 1, colunas, 2);   /* Testa a validade da entrada do usuario */
+
+    *lasty = *lasty - 1;    /* Ajusta a entrada do usuario para caber na matriz */
+    *lastx = *lastx - 1;    /* Ajusta a entrada do usuario para caber na matriz */
+
+    while(player2[*lasty][*lastx][1] == 1) {    /* Laco para garantir que o jogador nao atire duas vezes no mesmo quadrante */
+        printf("Voce ja atirou nesse quadrante. Escolha outro:\n");
+        printf("\n Proxima jogada: (linha)\t");     /* Pergunta e recebe a proxima linha a ser atirada */
+        scanf("%i", lasty);
+
+        printf("\n Proxima jogada: (coluna)\t");    /* Pergunta e recebe a proxima coluna a ser atirada */
+        scanf("%i", lastx);
+
+        teste(*lasty, 1, linhas, 2);            /* Testa a validade da entrada do usuario */
+        teste(*lastx, 1, colunas, 2);           /* Testa a validade da entrada do usuario */
+
+        *lasty = *lasty - 1;                    /* Ajuste das entradas do usuario para seu uso na matriz */
+        *lastx = *lastx - 1; }                  /* Fim do laco */
+
+    player2[*lasty][*lastx][1] = 1;             /* Define o quadrante como "atirado" */
+
+    for (j = 1; j < 20; j++)
+        printf("\n");   /* Quebra de linha tatica */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador adversario*/
+
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player2[j][k][1] == 0)  /* Caso o jogador nao tenha atirado no quadrante em questao, ele vera um caractere '?' */
+                printf("| ?");
+            else                        /* Caso contrario, ele vera o elemento guardado no quadrante em questao */
+                printf("|%2c", player2[j][k][0]);
+        }
+        printf("|\n");
+    }                                   /* Fim da impressao do tabuleiro do jogador adversario */
+
+    if (player2[*lasty][*lastx][0] == '~')  /* Imprime o resultado do tiro (agua) */
+        printf("Voce acertou a agua, marujo! Mire melhor a proxima!\n");
+
+    else {                                  /* Imprime o resultado do tiro (embarcacao) */
+        printf("Ahoy! Voce acertou alguma coisa ali!\n");
+        lifepl--; }                         /* Reduz a vida do jogador que levou o tiro */
+
+return(lifepl); }   /* Retorna o valor da vida do jogador */ /* ----Fim da funcao brief1----- */
+
+int brief2 (int ***player1, int ***player2, int *lastx, int *lasty, int *pontlife, int linhas, int colunas, int lifepl) {  /* Funcao brief1: Executa o jogo em si para o jogador 1 */
+
+    int i, j;       /* Variaveis de contagem */
+    int bool = 0;   /* Variavel para evitar que um jogador veja o tabuleiro do outro */
+
+    while (bool != 1) { /* Laco para evitar que um jogador veja o tabuleiro do outro */
+        printf("Mesmo? (Sim: 1| Nao: 0)\n");
+        scanf("%i", &bool);
+
+        teste(bool, 0, 1, 1); } /* Fim do laco com um teste da validade da entrada do usuario */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador atual*/
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player2[j][k][0] != '~' && player2[j][k][1] == 1)   /* Caso o quadrante em questao possua uma embarcacao e ja tenha sido atirado, imprime o caractere '*' */
+                printf("| *");
+            else                                                    /* Caso contrario, imprime a propria designacao */
+            printf("|%2c", player2[j][k][0]); }
+
+        if (j == 1)
+            printf("|\t Ultima jogada (L): %2i\n", *lasty+1);   /* Imprime a ultima jogada do player ao lado de seu tabuleiro */
+
+        else if (j == 2)
+            printf("|\t Ultima jogada (C): %2i\n", *lastx+1);   /* Imprime a ultima jogada do player ao lado de seu tabuleiro */
+
+        else if (j == 3)
+            printf("|\t Seu life: %2i\n", *pontlife);       /* Imprime o life do player ao lado de seu tabuleiro */
+
+        else if (j == 4)
+            printf("|\t Life do adversario: %2i\n", lifepl);/* Imprime o life do adversario ao lado do tabuleiro  do player*/
+
+        else
+            printf("|\n");                                  /* Imprime o caractere '|' e a quebra de linha nas linhas seguintes */
+    }                                           /* Fim da impressao */
+    printf("\nSeu tabuleiro eh o de cima\n\n"); /* Impressao de uma pequena informacao pertinente */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador adversario*/
+
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player1[j][k][1] == 0)              /* Caso o jogador nao tenha atirado no quadrante em questao, ele vera um caractere '?' */
+                printf("| ?");
+            else                                    /* Caso contrario, ele vera o elemento guardado no quadrante em questao */
+                printf("|%2c", player1[j][k][0]);
+        }
+        printf("|\n");
+    }                               /* Fim da impressao do tabuleiro do jogador adversario */
+
+    printf("\n Proxima jogada: (linha)\t");     /* Pergunta e recebe a proxima linha a ser atirada */
+    scanf("%i", lasty);
+
+    printf("\n Proxima jogada: (coluna)\t");    /* Pergunta e recebe a proxima linha a ser atirada */
+    scanf("%i", lastx);
+
+        teste(*lasty, 1, linhas, 2);    /* Testa a validade da entrada do usuario */
+        teste(*lastx, 1, colunas, 2);   /* Testa a validade da entrada do usuario */
+
+    *lasty = *lasty - 1;    /* Ajuste da entrada do usuario para o uso na matriz */
+    *lastx = *lastx - 1;    /* Ajuste da entrada do usuario para o uso na matriz */
+
+    while(player1[*lasty][*lastx][1] == 1) {
+        printf("Voce ja atirou nesse quadrante. Escolha outro:\n");
+        printf("\n Proxima jogada: (linha)\t");     /* Pergunta e recebe a proxima linha a ser atirada */
+        scanf("%i", lasty);
+
+        printf("\n Proxima jogada: (coluna)\t");    /* Pergunta e recebe a proxima linha a ser atirada */
+        scanf("%i", lastx);
+
+        teste(*lasty, 1, linhas, 2);    /* Testa a validade da entrada do usuario */
+        teste(*lastx, 1, colunas, 2);   /* Testa a validade da entrada do usuario */
+
+        *lasty = *lasty - 1;            /* Ajuste das entradas do usuario para o uso na matriz */
+        *lastx = *lastx - 1; }          /* Fim do laco */
+
+    player1[*lasty][*lastx][1] = 1;     /* Define o quadrante como "atirado" */
+
+    for (j = 1; j < 20; j++)
+        printf("\n");   /* Quebra de linha tatica */
+
+    printf("  ");                       /* Impressao do tabuleiro do jogador adversario*/
+
+    for (j = 1; j <= colunas; j++)
+        printf("|%2i", j);
+
+    printf("|\n");
+
+    for (j = 0; j < linhas; j++) {
+        printf("%2i", j+1);
+
+        for (int k = 0; k < colunas; k++) {
+            if (player1[j][k][1] == 0)              /* Caso o jogador nao tenha atirado no quadrante em questao, ele vera um caractere '?' */
+                printf("| ?");
+            else                                    /* Caso contrario, ele vera o elemento guardado no quadrante em questao */
+                printf("|%2c", player1[j][k][0]);
+        }
+        printf("|\n");
+    }                               /* Fim da impressao do tabuleiro do jogador adversario */
+
+    if (player1[*lasty][*lastx][0] == '~')  /* Imprime o resultado do tiro (agua) */
+        printf("Voce acertou a agua, marujo! Mire melhor a proxima!\n");
+
+    else {                                  /* Imprime o resultado do tiro (embarcacao) */
+        printf("Ahoy! Voce acertou alguma coisa ali!\n");
+        lifepl--; }                         /* Reduz a vida do jogador que levou o tiro */
+
+return(lifepl); }   /* Retorna o valor da vida do jogador */ /* ----Fim da funcao brief2----- */


comment

comment

--- sliod/slvr.c
+++ sliod/slvr.c
@@ -997,6 +997,10 @@
 		if (!SLVR_TRYLOCK(s))
 			continue;

+		/*
+		 * We do not check SLVRF_FAULTING here because we
+		 * are not looking at the CRC list (sli_crcqslvrs).
+		 */
 		if (s->slvr_refcnt || (s->slvr_flags & SLVRF_FREEING)) {
 			SLVR_ULOCK(s);
 			continue;


NB#102544: favor rebooting over actdead

NB#102544: favor rebooting over actdead

git-svn-id: 97ee0374337b904e4860f9ce78362f550003d14d@12023 db81c003-b5ea-0310-aa99-ed7f6e1db739

--- modules/state.c
+++ modules/state.c
@@ -206,20 +206,24 @@
       } else if (device_overheated) {
           dsme_log(LOG_CRIT, "Thermal shutdown!");
           state = DSME_STATE_SHUTDOWN;
-      } else if (shutdown_requested) {
-          if (charger_state != CHARGER_DISCONNECTED || alarm_set) {
+      } else if (shutdown_requested || reboot_requested) {
+          /* favor normal shutdown over reboot over actdead */
+          if (shutdown_requested &&
+              charger_state == CHARGER_DISCONNECTED &&
+              !alarm_set)
+          {
+              dsme_log(LOG_CRIT, "Normal shutdown");
+              state = DSME_STATE_SHUTDOWN;
+          } else if (reboot_requested) {
+              dsme_log(LOG_CRIT, "Reboot");
+              state = DSME_STATE_REBOOT;
+          } else{
               dsme_log(LOG_CRIT,
                        "Actdead (charger: %s, alarm: %s)",
                        charger_state == CHARGER_CONNECTED ? "on"  : "off(?)",
                        alarm_set                          ? "set" : "not set");
               state = DSME_STATE_ACTDEAD;
-          } else {
-              dsme_log(LOG_CRIT, "Normal shutdown");
-              state = DSME_STATE_SHUTDOWN;
           }
-      } else if (reboot_requested) {
-          dsme_log(LOG_CRIT, "Reboot");
-          state = DSME_STATE_REBOOT;
       } else {
           state = DSME_STATE_USER;
       }


libfreerdp-core: fix http encoding for TSG on Windows

--- libfreerdp/core/http.c
+++ libfreerdp/core/http.c
@@ -149,15 +149,77 @@
 	http_request->AuthParam = xstrdup(auth_param);
 }

-#ifdef _WIN32
-#define http_encode_line(_str, _fmt, ...) \
-	_str = xmalloc(sprintf_s(NULL, 0, _fmt, ## __VA_ARGS__) + 1); \
-	sprintf_s(_str, sprintf_s(NULL, 0, _fmt, ## __VA_ARGS__) + 1, _fmt, ## __VA_ARGS__);
-#else
-#define http_encode_line(_str, _fmt, ...) \
-	_str = xmalloc(snprintf(NULL, 0, _fmt, ## __VA_ARGS__) + 1); \
-	snprintf(_str, snprintf(NULL, 0, _fmt, ## __VA_ARGS__) + 1, _fmt, ## __VA_ARGS__);
+#ifndef _WIN32
+
+#ifndef errno_t
+typedef int errno_t;
 #endif
+
+errno_t _itoa_s(int value, char* buffer, size_t sizeInCharacters, int radix)
+{
+	int length;
+
+	length = snprintf(NULL, 0, "%d", value);
+
+	if (sizeInCharacters < length)
+		return -1;
+
+	snprintf(buffer, length + 1, "%d", value);
+
+	return 0;
+}
+
+#endif
+
+char* http_encode_body_line(char* param, char* value)
+{
+	char* line;
+	int length;
+
+	length = strlen(param) + strlen(value) + 2;
+	line = (char*) malloc(length + 1);
+	sprintf_s(line, length + 1, "%s: %s", param, value);
+
+	return line;
+}
+
+char* http_encode_content_length_line(int ContentLength)
+{
+	char* line;
+	int length;
+	char str[32];
+
+	_itoa_s(ContentLength, str, sizeof(str), 10);
+	length = strlen("Content-Length") + strlen(str) + 2;
+	line = (char*) malloc(length + 1);
+	sprintf_s(line, length + 1, "Content-Length: %s", str);
+
+	return line;
+}
+
+char* http_encode_header_line(char* Method, char* URI)
+{
+	char* line;
+	int length;
+
+	length = strlen("HTTP/1.1") + strlen(Method) + strlen(URI) + 2;
+	line = (char*) malloc(length + 1);
+	sprintf_s(line, length + 1, "%s %s HTTP/1.1", Method, URI);
+
+	return line;
+}
+
+char* http_encode_authorization_line(char* AuthScheme, char* AuthParam)
+{
+	char* line;
+	int length;
+
+	length = strlen("Authorization") + strlen(AuthScheme) + strlen(AuthParam) + 3;
+	line = (char*) malloc(length + 1);
+	sprintf_s(line, length + 1, "Authorization: %s %s", AuthScheme, AuthParam);
+
+	return line;
+}

 STREAM* http_request_write(HttpContext* http_context, HttpRequest* http_request)
 {
@@ -166,25 +228,24 @@
 	int length = 0;

 	http_request->count = 9;
-	http_request->lines = (char**) xmalloc(sizeof(char*) * http_request->count);
-
-	http_encode_line(http_request->lines[0], "%s %s HTTP/1.1", http_request->Method, http_request->URI);
-	http_encode_line(http_request->lines[1], "Cache-Control: %s", http_context->CacheControl);
-	http_encode_line(http_request->lines[2], "Connection: %s", http_context->Connection);
-	http_encode_line(http_request->lines[3], "Pragma: %s", http_context->Pragma);
-	http_encode_line(http_request->lines[4], "Accept: %s", http_context->Accept);
-	http_encode_line(http_request->lines[5], "User-Agent: %s", http_context->UserAgent);
-	http_encode_line(http_request->lines[6], "Content-Length: %d", http_request->ContentLength);
-	http_encode_line(http_request->lines[7], "Host: %s", http_context->Host);
+	http_request->lines = (char**) malloc(sizeof(char*) * http_request->count);
+
+	http_request->lines[0] = http_encode_header_line(http_request->Method, http_request->URI);
+	http_request->lines[1] = http_encode_body_line("Cache-Control", http_context->CacheControl);
+	http_request->lines[2] = http_encode_body_line("Connection", http_context->Connection);
+	http_request->lines[3] = http_encode_body_line("Pragma", http_context->Pragma);
+	http_request->lines[4] = http_encode_body_line("Accept", http_context->Accept);
+	http_request->lines[5] = http_encode_body_line("User-Agent", http_context->UserAgent);
+	http_request->lines[6] = http_encode_content_length_line(http_request->ContentLength);
+	http_request->lines[7] = http_encode_body_line("Host", http_context->Host);

 	if (http_request->Authorization != NULL)
 	{
-		http_encode_line(http_request->lines[8], "Authorization: %s", http_request->Authorization);
+		http_request->lines[8] = http_encode_body_line("Authorization", http_request->Authorization);
 	}
 	else if ((http_request->AuthScheme != NULL) && (http_request->AuthParam != NULL))
 	{
-		http_encode_line(http_request->lines[8], "Authorization: %s %s",
-				http_request->AuthScheme, http_request->AuthParam);
+		http_request->lines[8] = http_encode_authorization_line(http_request->AuthScheme, http_request->AuthParam);
 	}

 	for (i = 0; i < http_request->count; i++)


only warn once when genotype string cannot be parsed

--- snp2h5/vcf.c
+++ snp2h5/vcf.c
@@ -134,6 +134,7 @@
 			  char *cur) {
   int gt_idx, hap1, hap2, i, n;
   static int warn_phase = TRUE;
+  static int warn_parse = TRUE;
   long expect_haps, n_haps;
   char gt_str[VCF_MAX_FORMAT];

@@ -178,8 +179,12 @@
 		    inner_tok);
 	    warn_phase = FALSE;
 	  } else {
-	    my_warn("%s:%d: could not parse genotype string '%s'\n",
-		    __FILE__, __LINE__, inner_tok);
+	    if(warn_parse) {
+	      my_warn("%s:%d: could not parse some genotype "
+		      "strings that look like: '%s'\n", __FILE__, __LINE__,
+		      inner_tok);
+	      warn_parse = FALSE;
+	    }
 	    hap1 = VCF_GTYPE_MISSING;
 	    hap2 = VCF_GTYPE_MISSING;
 	  }


Fix console width thing on Windows.

Fix console width thing on Windows.

Also respect already existing line breaks when adding new ones to a
buffer.

--- cargo.c
+++ cargo.c
@@ -23,7 +23,7 @@
 		return -1;
 	}

-	return (int)(csbi.srWindow.Right - csbi.srWindow.Left + 1);
+	return (int)(csbi.srWindow.Right - csbi.srWindow.Left);

 	#else // Unix

@@ -592,6 +592,9 @@

 	if ((console_width = cargo_get_console_width()) > 0)
 	{
+		#ifdef _WIN32
+		console_width -= 8;
+		#endif
 		c->usage.max_width = console_width;
 	}

@@ -942,17 +945,25 @@
 	if (!s)
 		return NULL;

-	p = strpbrk(s, " ");
+	// TODO: If we already have a linebreak, use that instead of adding a new one.
+	p = strpbrk(s, " \n");
 	while (p != NULL)
 	{
-		if ((size_t)(p - start) > width)
-		{
+		// Restart on already existing explicit line breaks.
+		if (*p == '\n')
+		{
+			start = p;
+		}
+		else if ((size_t)(p - start) > width)
+		{
+			// We found a word that goes beyond the width we're
+			// aimin for, so add the line break before that word.
 			*prev = '\n';
 			start = p;
 		}

 		prev = p;
-		p = strpbrk(p + 1, " ");
+		p = strpbrk(p + 1, " \n");
 	}

 	return s;
@@ -963,7 +974,7 @@
 	int ret = 0;
 	size_t i;
 	size_t j;
-	int pos = 0;
+	int pos;
 	char *b;
 	char **namebufs = NULL;
 	int desclen = 0;
@@ -972,6 +983,7 @@
 	assert(ctx);
 	assert(buf);
 	#define MAX_OPT_NAME_LEN 40
+	#define NAME_PADDING 3

 	// First get option names and their length.
 	// We get the widest one so we know the column width to use
@@ -998,16 +1010,22 @@
 		}

 		if (namelen > max_name_len)
+		{
 			max_name_len = namelen;
+		}

 		desclen += namelen + strlen(ctx->options[i].description);
 	}

 	if (ctx->description && !(ctx->usage.format & CARGO_FORMAT_HIDE_DESCRIPTION))
-		desclen += strlen(ctx->description);
+	{
+		desclen += strlen(ctx->description);
+	}

 	if (ctx->epilog && !(ctx->usage.format & CARGO_FORMAT_HIDE_EPILOG))
+	{
 		desclen += strlen(ctx->epilog);
+	}

 	// Add some extra to fit padding.
 	desclen = (int)(desclen * 2.5);
@@ -1027,10 +1045,14 @@

 	// Output to the buffer.
 	*buf = b;
+	pos = 0;

 	if(ctx->description && !(ctx->usage.format & CARGO_FORMAT_HIDE_DESCRIPTION))
+	{
 		pos += cargo_snprintf(&b[pos], (desclen - pos), "%s\n\n", ctx->description);
-
+	}
+
+	// TODO: Replace cargo_snprintf(&b[pos], (desclen - pos) .... with a cargo_appendf function instead.
 	pos += cargo_snprintf(&b[pos], (desclen - pos), "Optional arguments:\n");

 	// Option names + descriptions.
@@ -1045,7 +1067,7 @@
 			|| (strlen(ctx->options[i].description) < ctx->usage.max_width))
 		{
 			pos += cargo_snprintf(&b[pos], (desclen - pos), "%*s%s\n",
-					2, "", ctx->options[i].description);
+					NAME_PADDING, "", ctx->options[i].description);
 		}
 		else
 		{
@@ -1053,10 +1075,11 @@
 			// Add line breaks to fit the width we want.
 			char **desc_lines = NULL;
 			size_t line_count = 0;
+
 			int padding = 0;
 			char *opt_description = _cargo_linebreak(ctx,
 								ctx->options[i].description,
-								ctx->usage.max_width - max_name_len - 4);
+								ctx->usage.max_width - max_name_len - (2 * NAME_PADDING));

 			if (!opt_description)
 			{
@@ -1072,7 +1095,7 @@
 			for (j = 0; j < line_count; j++)
 			{
 				// First line does not need the extra padding.
-				padding = (j == 0) ? 0 : (max_name_len + 2);
+				padding = (j == 0) ? (NAME_PADDING / 2) : (max_name_len + NAME_PADDING);

 				pos += cargo_snprintf(&b[pos], (desclen - pos), "  %*s%s\n",
 					padding, "",
@@ -1177,7 +1200,7 @@
 	args.poem_count = 0;
 	ret |= cargo_addv(cargo, "--poems", args.poems, &args.poem_count, 3,
 				CARGO_STRING,
-				"The poems. A very very long description for an option, "
+				"The poems. A very very long descriptionfor an option, "
 				"this couldn't possibly fit just one line, let's see if "
 				"we get any more?");


added check for '\r' in newline test

added check for '\r' in newline test

--- pygr/apps/maf2nclist.c
+++ pygr/apps/maf2nclist.c
@@ -84,7 +84,7 @@
       }
     }

-    if (tmp[l-1]=='\n') /* CHECK FOR START OF NEW LINE FOLLOWING...*/
+    if (tmp[l-1]=='\n' || tmp[l-1]=='\r') /* CHECK FOR START OF NEW LINE FOLLOWING...*/
       newline=1;
     else
       newline=0;


Add USAGE message

Add USAGE message

--- src/ocelot2.c
+++ src/ocelot2.c
@@ -1,6 +1,11 @@
 #include "scanner/scanner.h"

-void main() {
+void main(int argc, char** argv) {
+	if(argc <= 2) {
+        printf("USAGE: ./ozelot2 input-file output-file\n");
+        return -1;
+    }
+
 	scanner_init();

 	while(current_symbol != T_EOF) {


make cryptotest compile after the latest changes to cryptodev.h


BUG: Missing declaration of InitializeSCCA

It was necessary to add the declaration so
that compilation could complete.

--- Utilities/antsSCCANObject.h
+++ Utilities/antsSCCANObject.h
@@ -340,6 +340,8 @@
   void ConstantProbabilityThreshold( VectorType& v_in, RealType probability_goal, bool allow_negative_weights );

   VectorType InitializeV( MatrixType p, unsigned long seed = 0 );
+
+  TRealType InitializeSCCA( unsigned int n_vecs, unsigned int seeder );

   VectorType ComputeVectorLaplacian( VectorType, ImagePointer );
   VectorType ComputeVectorGradMag( VectorType, ImagePointer );


Add license

Add license

--- timing-test.c
+++ timing-test.c
@@ -1,3 +1,24 @@
+/* Copyright (c) 2013 AJ Stubberud. All rights reserved.
+*
+* Permission is hereby granted, free of charge, to any person obtaining a
+* copy of this software and associated documentation files (the "Software"),
+* to deal in the Software without restriction, including without limitation
+* the rights to use, copy, modify, merge, publish, distribute, sublicense,
+* and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in
+* all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+* DEALINGS IN THE SOFTWARE.
+*/
+
 #include "lib/timing.h"

 task main()


remove unnecessary list for args

remove unnecessary list for args

--- src/provenance_rewriter/game_provenance/gp_bottom_up_program.c
+++ src/provenance_rewriter/game_provenance/gp_bottom_up_program.c
@@ -439,7 +439,7 @@
         	    int curBitVec = j;
         		int pos, k;
 //        		List *searchBoolArgs = NIL;
-                List *boolArgs = NIL;
+//                List *boolArgs = NIL;

         		// represent all the possible bit flip for boolean args
 				for (pos = 0; pos < numGoals; pos++)
@@ -452,7 +452,7 @@
 						numArgs[pos] = FALSE;

 	        		//add into the list
-					boolArgs = appendToTailOfList(boolArgs, createConstBool(numArgs[pos]));
+//					boolArgs = appendToTailOfList(boolArgs, createConstBool(numArgs[pos]));
 					newRuleArg = appendToTailOfList(newRuleArg, createConstBool(numArgs[pos]));
 //					searchBoolArgs = appendToTailOfListInt(searchBoolArgs, numArgs[pos]);
   				}


avoid re-defining some win32/msvc settings if already set

i.e. from project settings

--- mordor/predef.h
+++ mordor/predef.h
@@ -5,15 +5,27 @@

 # ifdef WINDOWS
 // Get Vista+ APIs
-#  define _WIN32_WINNT 0x0600
+#  ifndef _WIN32_WINNT
+#    define _WIN32_WINNT 0x0600
+#  endif
 // Don't include tons of crap from windows.h
-#  define WIN32_LEAN_AND_MEAN
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
 // Define this so security.h works
-#  define SECURITY_WIN32
+#  ifndef SECURITY_WIN32
+#    define SECURITY_WIN32
+#  endif
 // Shut up, CRT
-#  define _CRT_SECURE_NO_WARNINGS
-#  define _CRT_NONSTDC_NO_WARNINGS
-#  define _SCL_SECURE_NO_WARNINGS
+#  ifndef _CRT_SECURE_NO_WARNINGS
+#    define _CRT_SECURE_NO_WARNINGS
+#  endif
+#  ifndef _CRT_NONSTDC_NO_WARNINGS
+#    define _CRT_NONSTDC_NO_WARNINGS
+#  endif
+#  ifndef _SCL_SECURE_NO_WARNINGS
+#    define _SCL_SECURE_NO_WARNINGS
+#  endif

 // Use more common names for functions
 // (cross-platform 64-bit, strip the underscores)


Added missing function comments to options.c.

--- src/options.c
+++ src/options.c
@@ -109,6 +109,7 @@
   {0, 0, 0, 0}
 };

+/* Command line help. */
 void
 cmd_help (void)
 {
@@ -245,6 +246,8 @@
 }
 /* *INDENT-ON* */

+/* Determine if the '--no-global-config' command line option needs to be
+ * enabled or not. */
 void
 verify_global_config (int argc, char **argv)
 {
@@ -274,6 +277,7 @@
   optind = 1;
 }

+/* Read the user's supplied command line options. */
 void
 read_option_args (int argc, char **argv)
 {


Moved --no-progress command line option to the UI set of options.

--- src/options.c
+++ src/options.c
@@ -121,6 +121,7 @@
   "  -c --config-dialog             - Prompt log/date configuration window.\n"
   "  -m --with-mouse                - Enable mouse support on main dashboard.\n"
   "  --color-scheme=<1|2>           - Color schemes: 1 => Grey, 2 => Green.\n"
+  "  --no-progress                  - Disable progress metrics.\n"
   "  --no-color                     - Disable colored output.\n\n"

   /* File Options */
@@ -151,7 +152,6 @@
   "  --ignore-crawlers              - Ignore crawlers.\n"
   "  --ignore-referer=<needle>      - Ignore a referer from being counted.\n"
   "                                   Wild cards are allowed. i.e., *.bing.com\n"
-  "  --no-progress                  - Disable progress metrics.\n\n"
   "  --real-os                      - Display real OS names. e.g, Windows XP,\n"
   "                                   Snow Leopard.\n"
   "  --sort-panel=PANEL,FIELD,ORDER - Sort panel on initial load. For example:\n"
@@ -164,7 +164,7 @@
 #ifdef HAVE_LIBGEOIP
   "GeoIP Options\n\n"
   "  -g --std-geoip                 - Standard GeoIP database for less memory\n"
-  "                                   usage.\n"
+  "                                   consumption.\n"
   "  --geoip-city-data=<path>       - Specify path to GeoIP City database file.\n"
   "                                   i.e., GeoLiteCity.dat\n\n"
 #endif


Support --no-recurse.

Support --no-recurse.

--- src/options.c
+++ src/options.c
@@ -102,6 +102,7 @@
         { "nofollow", no_argument, &(opts.follow_symlinks), 0 },
         { "heading", no_argument, &(opts.print_heading), 1 },
         { "noheading", no_argument, &(opts.print_heading), 0 },
+        { "no-recurse", no_argument, NULL, 'n' },
         { "help", no_argument, &help, 1 },
         { "ignore-case", no_argument, NULL, 'i' },
         { "files-with-matches", no_argument, NULL, 'l' },
@@ -136,7 +137,7 @@
     }

     /* TODO: check for insane params. nobody is going to want 5000000 lines of context, for example (on second thought, somebody might?) */
-    while ((ch = getopt_long(argc, argv, "A:aB:C:G:DfilvVu", longopts, &opt_index)) != -1) {
+    while ((ch = getopt_long(argc, argv, "A:aB:C:G:DfilnvVu", longopts, &opt_index)) != -1) {
         switch (ch) {
             case 'A':
                 opts.after = atoi(optarg);
@@ -178,6 +179,9 @@
                 break;
             case 'l':
                 opts.print_filename_only = 1;
+                break;
+            case 'n':
+                opts.recurse_dirs = 0;
                 break;
             case 'u':
                 opts.search_binary_files = 1;


entropy: Rename sysctl_wrapper to sysctl_arnd_wrapper

Signed-off-by: nia <5ad140d5f4b7cad9d45ac9c0d051724ab2960e88@netbsd.org>

--- library/entropy_poll.c
+++ library/entropy_poll.c
@@ -129,7 +129,7 @@
 #if defined(KERN_ARND)
 #define HAVE_SYSCTL_ARND

-static int sysctl_wrapper ( void *buf, size_t buflen )
+static int sysctl_arnd_wrapper( void *buf, size_t buflen )
 {
     int name[2];
     size_t len;
@@ -177,7 +177,7 @@
 #if defined(HAVE_SYSCTL_ARND)
     ((void) file);
     ((void) read_len);
-    if( sysctl_wrapper( output, len ) == -1 )
+    if( sysctl_arnd_wrapper( output, len ) == -1 )
         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
     *olen = len;
     return( 0 );


test: shim system.c system_get_chip props

Add test that verifies the system_get_chip_vendor/name/revision() all
invoke the chip-specific cros_system device driver routines.

BRANCH=none
BUG=b:236074898
TEST=twister --clobber -i -s zephyr/test/system_shim/system_shim.default

Signed-off-by: Aaron Massey <79529a820df71f45023239a3663736629646cc34@google.com>
Change-Id: I1291ec392c69f8fa6f81dc7fa1a567296a4f4df7
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/ec/+/3935638
Reviewed-by: Al Semjonovs <c3a2ecb550cad1e7d5a943ca6241377f7b43ffc4@google.com>
Code-Coverage: Zoss <345cf107e82c70959d46f59d98bddc98ce458aff@prod.google.com>

--- zephyr/test/system_shim/test_system.c
+++ zephyr/test/system_shim/test_system.c
@@ -28,6 +28,12 @@
 		const struct device *);
 FAKE_VALUE_FUNC(int, cros_system_native_posix_hibernate, const struct device *,
 		uint32_t, uint32_t);
+FAKE_VALUE_FUNC(const char *, cros_system_native_posix_get_chip_vendor,
+		const struct device *);
+FAKE_VALUE_FUNC(const char *, cros_system_native_posix_get_chip_name,
+		const struct device *);
+FAKE_VALUE_FUNC(const char *, cros_system_native_posix_get_chip_revision,
+		const struct device *);

 static void system_before_after(void *test_data)
 {
@@ -148,6 +154,37 @@
 		      sys_dev);
 	zassert_equal(cros_system_native_posix_hibernate_fake.arg1_val, secs);
 	zassert_equal(cros_system_native_posix_hibernate_fake.arg2_val, msecs);
+}
+
+ZTEST(system, test_system_get_chip_values)
+{
+	const struct device *sys_dev = device_get_binding("CROS_SYSTEM");
+
+	zassert_not_null(sys_dev);
+
+	/* Vendor */
+	cros_system_native_posix_get_chip_vendor_fake.return_val = "a";
+	zassert_mem_equal(system_get_chip_vendor(), "a", sizeof("a"));
+	zassert_equal(cros_system_native_posix_get_chip_vendor_fake.call_count,
+		      1);
+	zassert_equal(cros_system_native_posix_get_chip_vendor_fake.arg0_val,
+		      sys_dev);
+
+	/* Name */
+	cros_system_native_posix_get_chip_name_fake.return_val = "b";
+	zassert_mem_equal(system_get_chip_name(), "b", sizeof("b"));
+	zassert_equal(cros_system_native_posix_get_chip_name_fake.call_count,
+		      1);
+	zassert_equal(cros_system_native_posix_get_chip_name_fake.arg0_val,
+		      sys_dev);
+
+	/* Revision */
+	cros_system_native_posix_get_chip_revision_fake.return_val = "c";
+	zassert_mem_equal(system_get_chip_revision(), "c", sizeof("c"));
+	zassert_equal(
+		cros_system_native_posix_get_chip_revision_fake.call_count, 1);
+	zassert_equal(cros_system_native_posix_get_chip_revision_fake.arg0_val,
+		      sys_dev);
 }

 ZTEST_USER(system, test_system_console_cmd__idlestats)


Fix bug in ubuntu compilation

Fix bug in ubuntu compilation

git-svn-id: 9714148d14941aebeae8d7f7841217f5ffc02bc5@2913 4143565c-f3ec-42ea-b729-f8ce0cf5cbc3

--- libs/au/OnOffMonitor.h
+++ libs/au/OnOffMonitor.h
@@ -70,9 +70,9 @@
             double t = cronometer.diffTime();

             if( on )
-                on_time = on_time += t;
+                on_time += t;
             else
-                off_time = off_time += t;
+                off_time += t;

             // Forgetting factor
             off_time *= pow( f , t );


remove .0f which isn't an int

remove .0f which isn't an int

git-svn-id: 28d9401aa571d5108e51b194aae6f24ca5964c06@35437 8cc4aa7f-3514-0410-904f-f2cc9021211c

--- libs/csutil/xmltinyp.h
+++ libs/csutil/xmltinyp.h
@@ -230,7 +230,7 @@

   virtual csRef<iDocumentAttributeIterator> GetAttributes ();
   virtual csRef<iDocumentAttribute> GetAttribute (const char* name);
-  virtual int GetAttributeValueAsInt (const char* name, int defaultValue = 0.0f);
+  virtual int GetAttributeValueAsInt (const char* name, int defaultValue = 0);
   virtual float GetAttributeValueAsFloat (const char* name, float defaultValue = 0.0f);
   virtual bool  GetAttributeValueAsBool (const char* name,
 					 bool defaultValue = false);


Add missing _Nullable specification

Add missing _Nullable specification

--- BraintreePayPal/PayPalOneTouch/Analytics/PPFPTITracker.h
+++ BraintreePayPal/PayPalOneTouch/Analytics/PPFPTITracker.h
@@ -33,7 +33,7 @@

 /// The delegate which actually sends the data
-@property (nonatomic, weak, readwrite) id<PPFPTINetworkAdapterDelegate> networkAdapterDelegate;
+@property (nonatomic, weak, readwrite, nullable) id<PPFPTINetworkAdapterDelegate> networkAdapterDelegate;

 /// Sends an event with various metrics and data
 ///


added more comments

added more comments

--- machine-learning/Action.h
+++ machine-learning/Action.h
@@ -8,6 +8,7 @@
 {
 	explicit Action(const int _action);

+	//numerical identifier for the action
 	const int action;

 	//function to call execute the associated action
@@ -15,6 +16,7 @@

 	//needs function pointer to actual action

+	//comparison operator for use by priority queue
 	bool operator==(const Action& target) const;
 };


do not resize client window if emart sizing is enabled

If smart-sizing option is enabled in windows client and the server's desktop resolution changes, do not change the size of the client window.
This is because I would assume that if the user has enabled smart-sizing, they would intend for the window to be set to a particular size and not change.
Also, when connecting to windows 10 client, `wf_desktop_resize()` is called once just after connect and so if wfreerdp is run with `/smart-sizing:WxH` then the window will start at the size `WxH` but then immediately change to the desktop resolution of the server which makes the `/smart-sizing:WxH` parameter effectively do nothing.

--- client/Windows/wf_client.c
+++ client/Windows/wf_client.c
@@ -191,7 +191,7 @@

 	if (wfc->fullscreen != TRUE)
 	{
-		if (wfc->hwnd)
+		if (wfc->hwnd && !settings->SmartSizing)
 			SetWindowPos(wfc->hwnd, HWND_TOP, -1, -1, settings->DesktopWidth + wfc->diff.x,
 			             settings->DesktopHeight + wfc->diff.y, SWP_NOMOVE);
 	}


Exposed -didChangeSelection

Exposed -didChangeSelection

git-svn-id: 0833b781a6984bca00fd44c5b8a33a6c879c84c9@8377 7b3f36aa-e6db-49c1-8b4c-66eac1997e64

--- Headers/ETLayoutItemGroup.h
+++ Headers/ETLayoutItemGroup.h
@@ -177,6 +177,7 @@

 /* Framework Private */

+- (void) didChangeSelection;
 - (id) initAsLayerItem;
 - (BOOL) isLayerItem;


Update tcopy for CAM.  (/dev/rst0 -> /dev/rsa0)

PR:		i386/8688
Submitted by:	Bill Trost <trost@cloud.rain.com>

--- usr.bin/tcopy/pathnames.h
+++ usr.bin/tcopy/pathnames.h
@@ -33,4 +33,4 @@
  *	@(#)pathnames.h	8.1 (Berkeley) 6/6/93
  */

-#define	_PATH_DEFTAPE	"/dev/rst0"
+#define	_PATH_DEFTAPE	"/dev/rsa0"


remove debug code left in by accident

remove debug code left in by accident

--- usr.sbin/rpc.lockd/kern.c
+++ usr.sbin/rpc.lockd/kern.c
@@ -113,8 +113,6 @@
 		syslog(LOG_ERR, "mkfifo: %s: %m", _PATH_LCKFIFO);
 		exit (1);
 	}
-#define linebug syslog(LOG_ERR, "lockd: %d", __LINE__);
-linebug

 	/*
 	 * Create a separate process, the client code is really a separate
@@ -129,7 +127,6 @@
 		return (child);
 	}

-linebug
 	signal(SIGHUP, client_cleanup);
 	signal(SIGTERM, client_cleanup);

@@ -138,7 +135,6 @@
 	owner.pid = getpid();
 	(void)gethostname(hostname, sizeof(hostname) - 1);

-linebug
 reopen:
 	/* Open the fifo for reading. */
 	if ((fd = open(_PATH_LCKFIFO, O_RDONLY /* | O_NONBLOCK */)) < 0)
@@ -151,14 +147,12 @@
 	FD_ZERO(&rdset);

 	for (;;) {
-linebug
 		/* Wait for contact... fifo's return EAGAIN when read with
 		 * no data
 		 */
 		FD_SET(fd, &rdset);
 		(void)select(fd + 1, &rdset, NULL, NULL, NULL);

-linebug
 		/* Read the fixed length message. */
 		if ((nr = read(fd, &msg, sizeof(msg))) == sizeof(msg)) {
 			if (d_args)
@@ -202,7 +196,6 @@
 				}
 			}
 		} else if (nr == -1) {
-linebug
 			if (errno != EAGAIN) {
 				syslog(LOG_ERR, "read: %s: %m", _PATH_LCKFIFO);
 				goto err;


Move call to ignore SIGPIPE signals before calling fork(),
so that both parent and child processes ignore this signal.

PR:             bin/97768
Submitted by:   Gea-Suan Lin <gslin at csie dot nctu dot edu dot tw>
MFC after:      3 days


Use value_as_bool in if_block

Use value_as_bool in if_block

--- src/execution_functions/if_block.c
+++ src/execution_functions/if_block.c
@@ -14,7 +14,7 @@
     if(result.type != BOOL){
         ERROR("Invalid result type for if statement conditional: %c", result.type);
     }
-    else if(result.data.bl){ // result is boolean true
+    if(value_as_bool(&result)){ // result is boolean true
         result = execute(ast->children[1], defined, scopes, max_depth - 1);
     }
     else { // result is boolean false


Add explicit platform macros for Nintendo Switch and Playstation 4 (#506)

* Add explicit platform macros for Nintendo Switch and Playstation 4

* Addressing PR feedback

--- Include/httpClient/config.h
+++ Include/httpClient/config.h
@@ -10,6 +10,8 @@
 #define HC_PLATFORM_IOS 21
 #define HC_PLATFORM_MAC 22
 #define HC_PLATFORM_GENERIC 100
+#define HC_PLATFORM_NINTENDO_SWITCH 111
+#define HC_PLATFORM_SONY_PLAYSTATION_4 121

 // These macros define the datamodels that libHttpClient knows about
 // (a datamodel defines the size of primitive types such as int and pointers)
@@ -99,6 +101,12 @@
 (HC_PLATFORM == HC_PLATFORM_MAC || HC_PLATFORM == HC_PLATFORM_IOS)
 #endif

+// HC_PLATFORM_IS_EXTERNAL describes platforms where the implementation is outside of the libHttpClient repository
+#if !defined(HC_PLATFORM_IS_EXTERNAL)
+#define HC_PLATFORM_IS_EXTERNAL \
+(HC_PLATFORM == HC_PLATFORM_NINTENDO_SWITCH || HC_PLATFORM == HC_PLATFORM_SONY_PLAYSTATION_4 || HC_PLATFORM == HC_PLATFORM_GENERIC)
+#endif
+
 #if defined(HC_PLATFORM_MSBUILD_GUESS) && (HC_PLATFORM_MSBUILD_GUESS != HC_PLATFORM)
     #error The platform guessed by MSBuild does not agree with the platform selected by config.h
 #endif


Adding socketAccepted time into TransportInfo and pass to the TServerObserver

Summary: We are passing the socketAccepted time from AsyncServerSocket to the Cpp2Worker (wangle::Acceptor). And we make TServerObserver to receive this timestamp so that it can react to it. e.g. log the time duration so that we have more knowledge about the preprocess stage of a socket.

Reviewed By: joshkirstein

Differential Revision: D32128092

fbshipit-source-id: 5639f4f959a4d7f87761d65b2857d98d37eface6

--- mcrouter/ThriftObserver.h
+++ mcrouter/ThriftObserver.h
@@ -25,7 +25,7 @@
         router_(router),
         startedShutdown_(startedShutdown) {}

-  void connAccepted() override final {
+  void connAccepted(const wangle::TransportInfo& /* info */) override final {
     if (!startedShutdown_->load()) {
       auto proxy = router_.getProxy(tlsWorkerThreadId);
       proxy->stats().increment(num_client_connections_stat);


Add explicit std:: namespace identifier to inline code in irtkUtil.h to silence Eclipse warnings.

--- packages/registration/include/irtkUtil.h
+++ packages/registration/include/irtkUtil.h
@@ -147,10 +147,10 @@
 inline void irtkHistory::Print()
 {
   if (_no > 0) {
-    cout << "Cache has " << _no << " entries" << endl;
-    cout << "Cache statistics: " << 100 * _success / (_success + _failed)
+    std::cout << "Cache has " << _no << " entries" << std::endl;
+    std::cout << "Cache statistics: " << 100 * _success / (_success + _failed)
          << " % hits (" << _success << " out of " << (_success + _failed)
-         << ")" << endl;
+         << ")" << std::endl;
   }
 }

@@ -163,7 +163,7 @@
 extern double GuessResolution(double, double);
 extern double GuessResolution(double, double, double);
 extern int GuessPadding(irtkGreyImage &);
-extern int read_line(istream &, char *, char *&);
+extern int read_line(std::istream &, char *, char *&);

 #ifdef HAS_VTK


Update UIResponder+ZKAdd.h

Update UIResponder+ZKAdd.h

--- ZKCategories/Classes/UIResponder/UIResponder+ZKAdd.h
+++ ZKCategories/Classes/UIResponder/UIResponder+ZKAdd.h
@@ -8,6 +8,49 @@

 #import <UIKit/UIKit.h>
 #import <Foundation/Foundation.h>
+
+/*!
+ * @code
+
+ @interface ZKViewController : UIViewController
+ @property (nonatomic, strong) NSDictionary<NSString *, NSInvocation *> *eventStrategy;
+ @end
+
+ @implementation ZKViewController
+
+ - (BOOL)responderDidReceiveEvent:(nonnull NSString *)eventName userInfo:(nullable id)userInfo {
+     NSInvocation *invocation = self.eventStrategy[eventName];
+     [invocation setArgument:&userInfo atIndex:2];
+     [invocation invokeWithTarget:self];
+     return NO;
+ }
+
+ - (NSInvocation *)createInvocationWithSelector:(SEL)selector {
+     NSMethodSignature *sig = [[self class] instanceMethodSignatureForSelector:selector];
+     NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
+     [invocation setSelector:selector];
+
+     return invocation;
+ }
+
+ - (NSDictionary<NSString *, NSInvocation *> *)eventStrategy {
+     if (_eventStrategy == nil) {
+         _eventStrategy = @{
+                                kBLGoodsDetailTicketEvent:[self createInvocationWithSelector:@selector(ticketEvent:)],
+                                kBLGoodsDetailPromotionEvent:[self createInvocationWithSelector:@selector(promotionEvent:)],
+                                kBLGoodsDetailScoreEvent:[self createInvocationWithSelector:@selector(scoreEvent:)],
+                                kBLGoodsDetailTargetAddressEvent:[self createInvocationWithSelector:@selector(targetAddressEvent:)],
+                                kBLGoodsDetailServiceEvent:[self createInvocationWithSelector:@selector(serviceEvent:)],
+                                kBLGoodsDetailSKUSelectionEvent:[self createInvocationWithSelector:@selector(skuSelectionEvent:)],
+                                };
+     }
+     return _eventStrategy;
+ }
+
+ @end
+
+ * @endcode
+ */

 @interface UIResponder (ZKAdd)


ArmPkg/ArmLib: Fixed MpCore macros

ArmPkg/ArmLib: Fixed MpCore macros

Signed-off-by: Olivier Martin <olivier.martin@arm.com>

git-svn-id: 5648d1bec6962b0a6d1d1b40eba8cf5cdb62da3d@13256 6f19259b-4bc3-4df7-8a09-765794883524

--- ArmPkg/Include/Library/ArmLib.h
+++ ArmPkg/Include/Library/ArmLib.h
@@ -89,13 +89,19 @@
   ARM_PROCESSOR_MODE_MASK       = 0x1F
 } ARM_PROCESSOR_MODE;

+
+//
+// ARM MP Core IDs
+//
 #define IS_PRIMARY_CORE(MpId) (((MpId) & PcdGet32(PcdArmPrimaryCoreMask)) == PcdGet32(PcdArmPrimaryCore))
-#define GET_CORE_ID(MpId)     ((MpId) & 0xFF)
-#define GET_CLUSTER_ID(MpId)  (((MpId) >> 8) & 0xFF)
+#define ARM_CORE_MASK         0xFF
+#define ARM_CLUSTER_MASK      (0xFF << 8)
+#define GET_CORE_ID(MpId)     ((MpId) & ARM_CORE_MASK)
+#define GET_CLUSTER_ID(MpId)  (((MpId) & ARM_CLUSTER_MASK) >> 8)
 // Get the position of the core for the Stack Offset (4 Core per Cluster)
 //   Position = (ClusterId * 4) + CoreId
-#define GET_CORE_POS(MpId)    ((((MpId) >> 6) & 0xFF) + ((MpId) & 0xFF))
-#define PRIMARY_CORE_ID       (PcdGet32(PcdArmPrimaryCore) & 0xFF)
+#define GET_CORE_POS(MpId)    ((((MpId) & ARM_CLUSTER_MASK) >> 6) + ((MpId) & ARM_CORE_MASK))
+#define PRIMARY_CORE_ID       (PcdGet32(PcdArmPrimaryCore) & ARM_CORE_MASK)

 ARM_CACHE_TYPE
 EFIAPI


Typo.

Typo.

--- src/out/dot.c
+++ src/out/dot.c
@@ -18,7 +18,7 @@
 		return;

 	case '|':
-		fprintf(f, "\\\|");
+		fprintf(f, "\\|");
 		return;

 	/* TODO: others */


iirdes|example: cleaning up example

iirdes|example: cleaning up example

--- examples/iirdes_example.c
+++ examples/iirdes_example.c
@@ -15,15 +15,16 @@
 // print usage/help message
 void usage()
 {
-    printf("iirdes_example [options]\n");
-    printf("  u/h   : print usage\n");
+    printf("iirdes_example -- infinite impulse response filter design\n");
+    printf("options (default values in []):\n");
+    printf("  u/h   : print usage/help\n");
     printf("  t     : filter type: [butter], cheby1, cheby2, ellip, bessel\n");
     printf("  b     : filter transformation: [LP], HP, BP, BS\n");
-    printf("  n     : filter order\n");
-    printf("  r     : passband ripple [dB]\n");
-    printf("  s     : stopband attenuation [dB]\n");
-    printf("  f     : passband cut-off [0,0.5]\n");
-    printf("  c     : center frequency (BP, BS cases) [0,0.5]\n");
+    printf("  n     : filter order, n > 0 [5]\n");
+    printf("  r     : passband ripple in dB (cheby1, ellip), r > 0 [1.0]\n");
+    printf("  s     : stopband attenuation in dB (cheby2, ellip), s > 0 [60.0]\n");
+    printf("  f     : passband cut-off, 0 < f < 0.5 [0.2]\n");
+    printf("  c     : center frequency (BP, BS cases), 0 < c < 0.5 [0.25]\n");
     printf("  o     : format [sos], tf\n");
     printf("          sos   : second-order sections form\n");
     printf("          tf    : regular transfer function form (potentially\n");
@@ -33,8 +34,8 @@

 int main(int argc, char*argv[]) {
     // options
-    unsigned int n=6;       // filter order
-    float fc = 0.25f;       // cutoff frequency (low-pass prototype)
+    unsigned int n=5;       // filter order
+    float fc = 0.20f;       // cutoff frequency (low-pass prototype)
     float f0 = 0.25f;       // center frequency (band-pass, band-stop)
     float slsl = 60.0f;     // stopband attenuation [dB]
     float ripple = 1.0f;    // passband ripple [dB]
@@ -45,13 +46,13 @@
     // band type
     liquid_iirdes_bandtype btype = LIQUID_IIRDES_LOWPASS;

-    // output format
+    // output format: second-order sections or transfer function
     enum {  IIRDES_EXAMPLE_SOS=0,
             IIRDES_EXAMPLE_TF
     } format = 0;

     int dopt;
-    while ((dopt = getopt(argc,argv,"uht:q:n:r:s:f:c:o:")) != EOF) {
+    while ((dopt = getopt(argc,argv,"uht:b:n:r:s:f:c:o:")) != EOF) {
         switch (dopt) {
         case 'u':
         case 'h':
@@ -74,7 +75,7 @@
                 exit(1);
             }
             break;
-        case 'q':
+        case 'b':
             if (strcmp(optarg,"LP")==0) {
                 btype = LIQUID_IIRDES_LOWPASS;
             } else if (strcmp(optarg,"HP")==0) {
@@ -112,6 +113,26 @@
         }
     }

+    // validate input
+    if (fc <= 0 || fc >= 0.5) {
+        fprintf(stderr,"error: %s, cutoff frequency out of range\n", argv[0]);
+        usage();
+        exit(1);
+    } else if (f0 < 0 || f0 > 0.5) {
+        fprintf(stderr,"error: %s, center frequency out of range\n", argv[0]);
+        usage();
+        exit(1);
+    } else if (ripple <= 0) {
+        fprintf(stderr,"error: %s, pass-band ripple out of range\n", argv[0]);
+        usage();
+        exit(1);
+    } else if (slsl <= 0) {
+        fprintf(stderr,"error: %s, stop-band ripple out of range\n", argv[0]);
+        usage();
+        exit(1);
+    }
+
+
     // number of analaog poles/zeros
     unsigned int npa = n;
     unsigned int nza;


Fix erroneous argument number check in preset command

--- tools/adcli.c
+++ tools/adcli.c
@@ -571,7 +571,7 @@
 	argc -= optind;
 	argv += optind;

-	if (argc < 2)
+	if (argc < 1)
 		errx (EUSAGE, "specify one or more host names of computer accounts to preset");

 	adcli_conn_set_allowed_login_types (conn, ADCLI_LOGIN_USER_ACCOUNT);


[AdgLDim] arrange() should be called after local_changed()

Reordered function calls while computing the marker1 layout to be
consistent with marker2 and with the common sense.

--- adg/adg-ldim.c
+++ adg/adg-ldim.c
@@ -703,8 +703,8 @@
     if (data->marker1 != NULL) {
         AdgEntity *marker1_entity = (AdgEntity *) data->marker1;
         adg_marker_set_segment(data->marker1, data->trail, to_outside ? 2 : 1);
+        adg_entity_local_changed(marker1_entity);
         adg_entity_arrange(marker1_entity);
-        adg_entity_local_changed(marker1_entity);
         cpml_extents_add(&extents, adg_entity_get_extents(marker1_entity));
     }


optimizer: fix bug

optimizer: fix bug

Repair a typo in b0f4a32049; thanks to Blake Johnson.

--- racket/src/racket/src/resolve.c
+++ racket/src/racket/src/resolve.c
@@ -3179,7 +3179,7 @@
   if (n) {
     f = (int *)scheme_malloc_atomic(sizeof(int) * n);
     for (i = 0; i < n; i++) {
-      f[i] = ui->flags[pos + (n - i -i)];
+      f[i] = ui->flags[pos + (n - i - 1)];
     }
     ui->depth -= n;
   } else


only close if open

only close if open

--- spit/utils.c
+++ spit/utils.c
@@ -1289,8 +1289,8 @@
   FILE *fp = fopen("/dev/kmsg", "at");
   if (fp) {
     fprintf(fp, "%s\n", orig);
-  }
-  fclose(fp);
+    fclose(fp);
+  }

   free(orig);
 }


pg_upgrade:  remove reference to autovacuum_multixact_freeze_max_age

autovacuum_multixact_freeze_max_age was added as a pg_ctl start
parameter in 9.3.X to prevent autovacuum from running.  However, only
some 9.3.X releases have autovacuum_multixact_freeze_max_age as it was
added in a minor PG 9.3 release.  It also isn't needed because -b turns
off autovacuum in 9.1+.

Without this fix, trying to upgrade from an early 9.3 release to 9.4
would fail.

Report by EDB

Backpatch through 9.3

--- contrib/pg_upgrade/server.c
+++ contrib/pg_upgrade/server.c
@@ -202,12 +202,13 @@
 #endif

 	/*
-	 * Using autovacuum=off disables cleanup vacuum and analyze, but freeze
-	 * vacuums can still happen, so we set autovacuum_freeze_max_age and
-	 * autovacuum_multixact_freeze_max_age to their maximums.  We assume all
-	 * datfrozenxid, relfrozenxid, and relminmxid values are less than a gap
-	 * of 2000000000 from the current xid counter, so autovacuum will not
-	 * touch them.
+	 * Since PG 9.1, we have used -b to disable autovacuum.  For earlier
+	 * releases, setting autovacuum=off disables cleanup vacuum and analyze,
+	 * but freeze vacuums can still happen, so we set autovacuum_freeze_max_age
+	 * to its maximum.  (autovacuum_multixact_freeze_max_age was introduced
+	 * after 9.1, so there is no need to set that.)  We assume all datfrozenxid
+	 * and relfrozenxid values are less than a gap of 2000000000 from the current
+	 * xid counter, so autovacuum will not touch them.
 	 *
 	 * Turn off durability requirements to improve object creation speed, and
 	 * we only modify the new cluster, so only use it there.  If there is a
@@ -215,13 +216,11 @@
 	 * win on ext4.
 	 */
 	snprintf(cmd, sizeof(cmd),
-		  "\"%s/pg_ctl\" -w -l \"%s\" -D \"%s\" -o \"-p %d%s%s %s%s%s\" start",
+		  "\"%s/pg_ctl\" -w -l \"%s\" -D \"%s\" -o \"-p %d%s%s %s%s\" start",
 		  cluster->bindir, SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
 			 (cluster->controldata.cat_ver >=
 			  BINARY_UPGRADE_SERVER_FLAG_CAT_VER) ? " -b" :
 			 " -c autovacuum=off -c autovacuum_freeze_max_age=2000000000",
-			 (GET_MAJOR_VERSION(cluster->major_version) >= 903) ?
-			 " -c autovacuum_multixact_freeze_max_age=2000000000" : "",
 			 (cluster == &new_cluster) ?
 	  " -c synchronous_commit=off -c fsync=off -c full_page_writes=off" : "",
 			 cluster->pgopts ? cluster->pgopts : "", socket_string);


Fix bug with multiple evaluation of tsearch2 compatibility trigger, trigger data should be restored. Backpatch only for 8.3 because previous versions haven't such layer.

--- contrib/tsearch2/tsearch2.c
+++ contrib/tsearch2/tsearch2.c
@@ -7,7 +7,7 @@
  *
  *
  * IDENTIFICATION
- *	  $PostgreSQL: pgsql/contrib/tsearch2/tsearch2.c,v 1.5 2008/01/01 19:45:45 momjian Exp $
+ *	  $PostgreSQL: pgsql/contrib/tsearch2/tsearch2.c,v 1.5.2.1 2009/01/28 18:32:55 teodor Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -372,8 +372,10 @@
 {
 	TriggerData *trigdata;
 	Trigger    *trigger;
-	char	  **tgargs;
+	char	  **tgargs,
+			  **tgargs_old;
 	int			i;
+	Datum		res;

 	/* Check call context */
 	if (!CALLED_AS_TRIGGER(fcinfo))		/* internal error */
@@ -393,10 +395,20 @@

 	tgargs[1] = pstrdup(GetConfigOptionByName("default_text_search_config",
 											  NULL));
+	tgargs_old = trigger->tgargs;
 	trigger->tgargs = tgargs;
 	trigger->tgnargs++;

-	return tsvector_update_trigger_byid(fcinfo);
+	res = tsvector_update_trigger_byid(fcinfo);
+
+	/* restore old trigger data */
+	trigger->tgargs = tgargs_old;
+	trigger->tgnargs--;
+
+	pfree(tgargs[1]);
+	pfree(tgargs);
+
+	return res;
 }


Give these functions a more appropriate type.

--- rts/c/util.h
+++ rts/c/util.h
@@ -26,14 +26,14 @@
 }

 // Read a file into a NUL-terminated string; returns NULL on error.
-static char* slurp_file(const char *filename, size_t *size) {
-  char *s;
+static void* slurp_file(const char *filename, size_t *size) {
+  unsigned char *s;
   FILE *f = fopen(filename, "rb"); // To avoid Windows messing with linebreaks.
   if (f == NULL) return NULL;
   fseek(f, 0, SEEK_END);
   size_t src_size = ftell(f);
   fseek(f, 0, SEEK_SET);
-  s = (char*) malloc(src_size + 1);
+  s = (unsigned char*) malloc(src_size + 1);
   if (fread(s, 1, src_size, f) != src_size) {
     free(s);
     s = NULL;
@@ -51,7 +51,7 @@

 // Dump 'n' bytes from 'buf' into the file at the designated location.
 // Returns 0 on success.
-static int dump_file(const char *file, const char *buf, size_t n) {
+static int dump_file(const char *file, const void *buf, size_t n) {
   FILE *f = fopen(file, "w");

   if (f == NULL) {


增加对一个数的二进制位的打印 以及生成对应的字符串

增加对一个数的二进制位的打印 以及生成对应的字符串

--- JOKit/JOKit/Macro/JOMacro.h
+++ JOKit/JOKit/Macro/JOMacro.h
@@ -51,6 +51,8 @@

 #pragma mark - base
 #pragma mark -
+
+#define JOBitsNum(_type_) sizeof(_type_)*8

 #define JOMetaConcat_(A, B) A ## B
 #define JOMetaConcat(A, B) JOMetaConcat_(A, B)
@@ -309,6 +311,48 @@
 #pragma mark - Function
 #pragma mark -

+JO_STATIC_INLINE void JOPrintBits_(size_t const size, void const *__nonnull const p) {
+    unsigned char *ptr = (unsigned char *)p;
+    unsigned char byte;
+    for (int i = (int)size - 1; i >= 0; i--) {
+        for (int j = JOBitsNum(byte)-1; j >= 0 ; j--) {
+            byte = ((ptr[i] >> j)&1) + '0';
+            printf("%c",byte);
+        }
+    }
+    printf("\n");
+}
+
+JO_STATIC_INLINE char *__nonnull JOBitsCharStr_(size_t const size, void const *__nonnull const p) {
+
+    unsigned char *ptr = (unsigned char *)p;
+    unsigned char byte;
+    char *pByte = malloc(size*8)+1; //多一位用来存放结束的标识符:\0
+    int tempPtr = 0;
+    for (int i = (int)size - 1; i >= 0; i--) {
+        for (int j = JOBitsNum(byte)-1; j >= 0 ; j--) {
+            byte = ((ptr[i] >> j)&1) + '0';
+            pByte[tempPtr] = byte;
+            tempPtr++;
+        }
+    }
+    pByte[tempPtr] = '\0';
+    return pByte;
+}
+
+#ifndef JOPrintBits
+#define JOPrintBits(_value_) JOPrintBits_(sizeof(_value_),&_value_)
+#endif
+
+#ifndef JOBitsCharStr
+#define JOBitsCharStr(_value_) JOBitsCharStr_(sizeof(_value_),&_value_)
+#endif
+
+#ifndef JOBitsString
+#define JOBitsString(_value_) [NSString stringWithUTF8String:JOBitsCharStr(_value_)]
+#endif
+
+
 /*Exception*/
 #ifndef JOThrowException
 #define JOThrowException(exceptionName , reason) \


Fixed the bug in the stracat function

Fixed the bug in the stracat function

git-svn-id: fbb392d5347ebc45c06187f72dfd8bab02595dbf@357142 13f79535-47bb-0310-9956-ffa450edef68

--- modules/util/src/string.c
+++ modules/util/src/string.c
@@ -58,7 +58,7 @@
     }
     if(NULL == s2)
     {
-        return (axis2_char_t)AXIS2_STRDUP(s1, env);
+        return (axis2_char_t *)AXIS2_STRDUP(s1, env);
     }
     alloc_len = axis2_strlen(s1) + axis2_strlen(s2) + 1;
     ret = (axis2_char_t*)AXIS2_MALLOC((*env)->allocator,


Fixed compilation error under GCC Linux 32 bits with zlib, issues with gpac includes

git-svn-id: 33bf1455041ebe448dbaea643fd5b4b7ce02239d@2889 63c20433-aa62-49bd-875c-5a186b69a8fb

--- modules/widgetman/unzip.c
+++ modules/widgetman/unzip.c
@@ -26,8 +26,8 @@

 #endif

+#include "unzip.h"
 #include <gpac/tools.h>
-# include "unzip.h"


不要になったメソッドの消し忘れ

不要になったメソッドの消し忘れ

--- BonDriverProxy/BonDriverProxy.h
+++ BonDriverProxy/BonDriverProxy.h
@@ -112,9 +112,6 @@
 	cProxyServer();
 	~cProxyServer();
 	void setSocket(SOCKET s){ m_s = s; }
-#ifdef HAVE_UI
-	void Shutdown(){ m_Error.Set(); }
-#endif
 	static DWORD WINAPI Reception(LPVOID pv);
 };


Refactor

Refactor

--- WebDemoLauncher/WebServer.h
+++ WebDemoLauncher/WebServer.h
@@ -37,8 +37,6 @@
 	bool isEndOfRequest(std::string request);
 	void createResponse(Connection &conn, std::string status, std::string contentType, std::string payload);
 	void handleRequest(Connection&, Request);
-	long getFileSize(std::string filename);
-	void transferFile(Connection& conn, std::string fileName);
 	bool WriteData(Connection& conn);
 	void SetupFDSets(fd_set& ReadFDs, fd_set& WriteFDs, fd_set& ExceptFDs);
 	std::string getFile(std::string fileName);
@@ -54,9 +52,9 @@

 class NetworkException : public std::exception {
 private:
-	char *reason;
+	std::string reason;
 public:
-	NetworkException(char *message) {
+	NetworkException(std::string message) {
 		reason = message;
 	}
 };


Improve information displayed about frame size.

git-svn-id: 8dbf393e6e9ab8d4979d29f9a341a98016792aa6@5142 0101bb08-14d6-0310-b084-bc0e0c8e3800

--- examples/player_example.c
+++ examples/player_example.c
@@ -12,7 +12,7 @@

   function: example SDL player application; plays Ogg Theora files (with
             optional Vorbis audio second stream)
-  last mod: $Id: player_example.c,v 1.24 2003/06/12 10:39:38 giles Exp $
+  last mod: $Id: player_example.c,v 1.25 2003/07/15 13:21:21 giles Exp $

  ********************************************************************/

@@ -545,9 +545,11 @@
   /* and now we have it all.  initialize decoders */
   if(theora_p){
     theora_decode_init(&td,&ti);
-    printf("Ogg logical stream %x is Theora %dx%d %.02f fps video\n"
-           "  Frame content is %dx%d with offset (%d,%d).\n",
-           to.serialno,ti.width,ti.height, (double)ti.fps_numerator/ti.fps_denominator,
+    printf("Ogg logical stream %x is Theora %dx%d %.02f fps video\n",
+           to.serialno,ti.width,ti.height,
+           (double)ti.fps_numerator/ti.fps_denominator);
+    if(ti.width!=ti.frame_width || ti.height!=ti.frame_height)
+      printf("  Frame content is %dx%d with offset (%d,%d).\n",
            ti.frame_width, ti.frame_height, ti.offset_x, ti.offset_y);
     report_colorspace(&ti);
     dump_comments(&tc);


seg fault fixes.

seg fault fixes.

(Logical change 1.647)

--- libseuser/seuser_tcl.c
+++ libseuser/seuser_tcl.c
@@ -323,7 +323,7 @@
 		return TCL_ERROR;
 	}
 	else if(rt != 0) {
-		Tcl_AppendResult(interp, "Error removing the user from the database");
+		Tcl_AppendResult(interp, "Error removing the user from the database", (char *) NULL);
 		return TCL_ERROR;
 	}

@@ -504,7 +504,7 @@

 	rt = seuser_write_user_file(&db, policy);
 	if(rt != 0) {
-		Tcl_AppendResult(interp, "Problem writing the user file");
+		Tcl_AppendResult(interp, "Problem writing the user file", (char *) NULL);
 		return TCL_ERROR;
 	}
 	return TCL_OK;


A couple 'const's to make that compile cleanly

git-svn-id: 42b1393cca5d551bec90c34575d0b84245f1dba8@5766 0101bb08-14d6-0310-b084-bc0e0c8e3800

--- libspeex/filters_sse.h
+++ libspeex/filters_sse.h
@@ -32,7 +32,7 @@

 #include <xmmintrin.h>

-void filter_mem2_10(float *x, float *_num, float *_den, float *y, int N, int ord, float *_mem)
+void filter_mem2_10(const float *x, const float *_num, const float *_den, float *y, int N, int ord, float *_mem)
 {
    __m128 num[3], den[3], mem[3];

@@ -85,7 +85,7 @@
    _mm_store_ss(_mem+9, mem[2]);
 }

-void filter_mem2_8(float *x, float *_num, float *_den, float *y, int N, int ord, float *_mem)
+void filter_mem2_8(const float *x, const float *_num, const float *_den, float *y, int N, int ord, float *_mem)
 {
    __m128 num[2], den[2], mem[2];

@@ -129,7 +129,7 @@

-void filter_mem2(float *x, float *_num, float *_den, float *y, int N, int ord, float *_mem)
+void filter_mem2(const float *x, const float *_num, const float *_den, float *y, int N, int ord, float *_mem)
 {
    if(ord==10)
       filter_mem2_10(x, _num, _den, y, N, ord, _mem);
@@ -139,7 +139,7 @@

-void iir_mem2_10(float *x, float *_den, float *y, int N, int ord, float *_mem)
+void iir_mem2_10(const float *x, const float *_den, float *y, int N, int ord, float *_mem)
 {
    __m128 den[3], mem[3];

@@ -188,7 +188,7 @@
 }

-void iir_mem2_8(float *x, float *_den, float *y, int N, int ord, float *_mem)
+void iir_mem2_8(const float *x, const float *_den, float *y, int N, int ord, float *_mem)
 {
    __m128 den[2], mem[2];

@@ -227,7 +227,7 @@
    _mm_storeu_ps(_mem+4, mem[1]);
 }

-void iir_mem2(float *x, float *_den, float *y, int N, int ord, float *_mem)
+void iir_mem2(const float *x, const float *_den, float *y, int N, int ord, float *_mem)
 {
    if(ord==10)
       iir_mem2_10(x, _den, y, N, ord, _mem);
@@ -236,7 +236,7 @@
 }

-void fir_mem2_10(float *x, float *_num, float *y, int N, int ord, float *_mem)
+void fir_mem2_10(const float *x, const float *_num, float *y, int N, int ord, float *_mem)
 {
    __m128 num[3], mem[3];

@@ -284,7 +284,7 @@
    _mm_store_ss(_mem+9, mem[2]);
 }

-void fir_mem2_8(float *x, float *_num, float *y, int N, int ord, float *_mem)
+void fir_mem2_8(const float *x, const float *_num, float *y, int N, int ord, float *_mem)
 {
    __m128 num[2], mem[2];

@@ -324,7 +324,7 @@
 }

-void fir_mem2(float *x, float *_num, float *y, int N, int ord, float *_mem)
+void fir_mem2(const float *x, const float *_num, float *y, int N, int ord, float *_mem)
 {
    if(ord==10)
       fir_mem2_10(x, _num, y, N, ord, _mem);


ms_client_get_volume_owner_id()

--- libsyndicate/ms/core.h
+++ libsyndicate/ms/core.h
@@ -165,6 +165,7 @@
 uint64_t ms_client_volume_version( struct ms_client* client );
 uint64_t ms_client_cert_version( struct ms_client* client );
 uint64_t ms_client_get_volume_id( struct ms_client* client );
+uint64_t ms_client_get_volume_owner_id( struct ms_client* client );
 uint64_t ms_client_get_owner_id( struct ms_client* client );
 uint64_t ms_client_get_gateway_id( struct ms_client* client );
 char* ms_client_get_volume_name( struct ms_client* client );


Create simple_example.c

Create simple_example.c

error: pathspec 'examples/simple_example.c' did not match any file(s) known to git

--- examples/simple_example.c
+++ examples/simple_example.c
@@ -0,0 +1,26 @@
+
+#include <stdio.h>
+#include "bddcore.h"
+
+
+int main(){
+	Bdd *bdd1, *bdd2, *bdd3;
+	char buff[2048];
+	gets_s(buff, 2048);
+	//example: a1&x1|(a3^1)
+	bdd1 = createBdd(buff);
+	gets_s(buff, 2048);
+	//example: (x1>y)|~z&y
+	bdd2 = createBdd(buff);
+
+	bdd3 = synthesizeBdd(bdd1, bdd2, 7, 1, 1);// bdd1|bdd2
+
+	fprintBdd(stdout, bdd1, 0);
+	printf("\n");
+	fprintBdd(stdout, bdd2, 0);
+	printf("\n");
+	fprintBdd(stdout, bdd3, 0);
+
+	freeBdd(bdd1); freeBdd(bdd2); freeBdd(bdd3);
+	getchar();
+}


Convert double quotes in a command help string to single quotes to allow the string to be processed by Javascript.

--- FreeRTOS-Plus/Source/FreeRTOS-Plus-CLI/FreeRTOS_CLI.c
+++ FreeRTOS-Plus/Source/FreeRTOS-Plus-CLI/FreeRTOS_CLI.c
@@ -206,7 +206,7 @@
 	else
 	{
 		/* pxCommand was NULL, the command was not found. */
-		strncpy( ( char * ) pcWriteBuffer, ( const char * const ) "Command not recognised.  Enter \"help\" to view a list of available commands.\r\n\r\n", xWriteBufferLen );
+		strncpy( ( char * ) pcWriteBuffer, ( const char * const ) "Command not recognised.  Enter 'help' to view a list of available commands.\r\n\r\n", xWriteBufferLen );
 		xReturn = pdFALSE;
 	}


Close resource leak.

Close resource leak.

--- monetdb5/mal/mal_linker.c
+++ monetdb5/mal/mal_linker.c
@@ -105,7 +105,7 @@
 MALfcn
 getAddress(stream *out, str filename, str modnme, str fcnname, int silent)
 {
-	void *dl = 0;
+	void *dl;
 	MALfcn adr;
 	static int idx=0;
 	static int prev= -1;
@@ -142,22 +142,27 @@
 	 * @-
 	 * Try the program libraries at large or run through all
 	 * loaded files and try to resolve the functionname again.
-	 */
+	 *
+	 * the first argument must be the same as the base name of the
+	 * library that is created in src/tools */
+	dl = mdlopen("libmonetdb5", RTLD_NOW | RTLD_GLOBAL);
 	if (dl == NULL) {
-		/* the first argument must be the same as the base name of the
-		 * library that is created in src/tools */
-		dl = mdlopen("libmonetdb5", RTLD_NOW | RTLD_GLOBAL);
-	}
-	if( dl != NULL){
-		adr = (MALfcn) dlsym(dl, fcnname);
-		if( adr != NULL)
-			return adr; /* found it */
-	}
+		/* shouldn't happen, really */
+		if (!silent)
+			showException(out, MAL, "MAL.getAddress",
+						  "address of '%s.%s' not found",
+						  (modnme?modnme:"<unknown>"), fcnname);
+		return NULL;
+	}
+
+	adr = (MALfcn) dlsym(dl, fcnname);
+	dlclose(dl);
+	if( adr != NULL)
+		return adr; /* found it */
+
 	if (!silent)
 		showException(out, MAL,"MAL.getAddress", "address of '%s.%s' not found",
 			(modnme?modnme:"<unknown>"), fcnname);
-	if ( dl)
-		dlclose(dl);
 	return NULL;
 }
 /*


Fix segfaults in libshogun GP examples

Fix segfaults in libshogun GP examples

--- src/shogun/evaluation/GradientResult.h
+++ src/shogun/evaluation/GradientResult.h
@@ -83,7 +83,7 @@
 		{
 			char* name = gradient.get_node_ptr(i)->key->m_name;
 			for (index_t j = 0; j < gradient.get_element_ptr(i)->vlen; j++)
-				SG_SPRINT("%s: %f, ", (*gradient.get_element_ptr(i))[j], name)
+				SG_SPRINT("%s: %f, ", name, (*gradient.get_element_ptr(i))[j])
 		}
 		SG_SPRINT("]\n")


Remove 0xc8000 check when searching PNP header. Remove the check about the size of Init code when validating if PCI 3.0 OPROM is successfully started.

Signed-off-by: Li Elvin <elvin.li@intel.com>
Reviewed-by: Ni Ruiyu <ruiyu.ni@intel.com>

git-svn-id: 5648d1bec6962b0a6d1d1b40eba8cf5cdb62da3d@13944 6f19259b-4bc3-4df7-8a09-765794883524

--- IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
+++ IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyPci.c
@@ -1500,54 +1500,52 @@
     }
   }

-  if (PciPtr >= (EFI_LEGACY_EXPANSION_ROM_HEADER *) ((UINTN) 0xc8000)) {
-    while (TRUE) {
-      Status    = FindNextPnpExpansionHeader (Private, Instance, &PnpPtr);
-      Instance  = NOT_FIRST_INSTANCE;
-      if (EFI_ERROR (Status)) {
-        break;
-      }
-      //
-      // There can be additional $PnP headers within the OPROM.
-      // Example: SCSI can have one per drive.
-      //
-      BbsTable[BbsIndex].BootPriority             = BBS_UNPRIORITIZED_ENTRY;
-      BbsTable[BbsIndex].DeviceType               = DeviceType;
-      BbsTable[BbsIndex].Bus                      = (UINT32) Bus;
-      BbsTable[BbsIndex].Device                   = (UINT32) Device;
-      BbsTable[BbsIndex].Function                 = (UINT32) Function;
-      BbsTable[BbsIndex].StatusFlags.OldPosition  = 0;
-      BbsTable[BbsIndex].StatusFlags.Reserved1    = 0;
-      BbsTable[BbsIndex].StatusFlags.Enabled      = 0;
-      BbsTable[BbsIndex].StatusFlags.Failed       = 0;
-      BbsTable[BbsIndex].StatusFlags.MediaPresent = 0;
-      BbsTable[BbsIndex].StatusFlags.Reserved2    = 0;
-      BbsTable[BbsIndex].Class                    = PnpPtr->Class;
-      BbsTable[BbsIndex].SubClass                 = PnpPtr->SubClass;
-      BbsTable[BbsIndex].DescStringOffset         = PnpPtr->ProductNamePointer;
-      BbsTable[BbsIndex].DescStringSegment        = mBbsRomSegment;
-      BbsTable[BbsIndex].MfgStringOffset          = PnpPtr->MfgPointer;
-      BbsTable[BbsIndex].MfgStringSegment         = mBbsRomSegment;
-      BbsTable[BbsIndex].BootHandlerSegment       = mBbsRomSegment;
-
-      //
-      // Have seen case where PXE base code have PnP expansion ROM
-      // header but no Bcv or Bev vectors.
-      //
-      if (PnpPtr->Bcv != 0) {
-        BbsTable[BbsIndex].BootHandlerOffset = PnpPtr->Bcv;
-        ++BbsIndex;
-      }
-
-      if (PnpPtr->Bev != 0) {
-        BbsTable[BbsIndex].BootHandlerOffset  = PnpPtr->Bev;
-        BbsTable[BbsIndex].DeviceType         = BBS_BEV_DEVICE;
-        ++BbsIndex;
-      }
-
-      if ((PnpPtr == (LEGACY_PNP_EXPANSION_HEADER *) PciPtr) || (PnpPtr > (LEGACY_PNP_EXPANSION_HEADER *) RomEnd)) {
-        break;
-      }
+  while (TRUE) {
+    Status    = FindNextPnpExpansionHeader (Private, Instance, &PnpPtr);
+    Instance  = NOT_FIRST_INSTANCE;
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+    //
+    // There can be additional $PnP headers within the OPROM.
+    // Example: SCSI can have one per drive.
+    //
+    BbsTable[BbsIndex].BootPriority             = BBS_UNPRIORITIZED_ENTRY;
+    BbsTable[BbsIndex].DeviceType               = DeviceType;
+    BbsTable[BbsIndex].Bus                      = (UINT32) Bus;
+    BbsTable[BbsIndex].Device                   = (UINT32) Device;
+    BbsTable[BbsIndex].Function                 = (UINT32) Function;
+    BbsTable[BbsIndex].StatusFlags.OldPosition  = 0;
+    BbsTable[BbsIndex].StatusFlags.Reserved1    = 0;
+    BbsTable[BbsIndex].StatusFlags.Enabled      = 0;
+    BbsTable[BbsIndex].StatusFlags.Failed       = 0;
+    BbsTable[BbsIndex].StatusFlags.MediaPresent = 0;
+    BbsTable[BbsIndex].StatusFlags.Reserved2    = 0;
+    BbsTable[BbsIndex].Class                    = PnpPtr->Class;
+    BbsTable[BbsIndex].SubClass                 = PnpPtr->SubClass;
+    BbsTable[BbsIndex].DescStringOffset         = PnpPtr->ProductNamePointer;
+    BbsTable[BbsIndex].DescStringSegment        = mBbsRomSegment;
+    BbsTable[BbsIndex].MfgStringOffset          = PnpPtr->MfgPointer;
+    BbsTable[BbsIndex].MfgStringSegment         = mBbsRomSegment;
+    BbsTable[BbsIndex].BootHandlerSegment       = mBbsRomSegment;
+
+    //
+    // Have seen case where PXE base code have PnP expansion ROM
+    // header but no Bcv or Bev vectors.
+    //
+    if (PnpPtr->Bcv != 0) {
+      BbsTable[BbsIndex].BootHandlerOffset = PnpPtr->Bcv;
+      ++BbsIndex;
+    }
+
+    if (PnpPtr->Bev != 0) {
+      BbsTable[BbsIndex].BootHandlerOffset  = PnpPtr->Bev;
+      BbsTable[BbsIndex].DeviceType         = BBS_BEV_DEVICE;
+      ++BbsIndex;
+    }
+
+    if ((PnpPtr == (LEGACY_PNP_EXPANSION_HEADER *) PciPtr) || (PnpPtr > (LEGACY_PNP_EXPANSION_HEADER *) RomEnd)) {
+      break;
     }
   }

@@ -2557,10 +2555,10 @@
   //
   // The ROM could have updated it's size so we need to read again.
   //
-  if ((((EFI_LEGACY_EXPANSION_ROM_HEADER *) RuntimeAddress)->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) &&
-      (((EFI_LEGACY_EXPANSION_ROM_HEADER *) InitAddress)->Size512 == 0)) {
-    //
-    // The INIT function didn't copy the RUNTIME code to RuntimeAddress
+  if (((EFI_LEGACY_EXPANSION_ROM_HEADER *) RuntimeAddress)->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) {
+    //
+    // Now we check the signature (0xaa55) to judge whether the run-time code is truly generated by INIT function.
+    // If signature is not valid, that means the INIT function didn't copy the run-time code to RuntimeAddress.
     //
     *RuntimeImageLength = 0;
   } else {


sterilize username to consistently handle usernames starting with '.'

--- myproxy_creds.c
+++ myproxy_creds.c
@@ -909,6 +909,7 @@
 	h_username = strmd5(username, NULL);
     } else {
 	h_username = strdup(creds->username);
+    sterilize_string(h_username);
     }
     h_username_len = strlen(h_username);
     owner_name = strdup(creds->owner_name);


- add myproxy_creds_verify_passphrase() to have passphrase logic in   one place. we verify the passphrase by either trying to decrypt the   key (new method) or comparing with the stashed crypted passphrase   (for backward compat) - don't write out crypted passphrase anymore. we can check the   passphrase by trying to decrypt the private key (new method)

--- myproxy_creds.c
+++ myproxy_creds.c
@@ -413,16 +413,7 @@
     FILE *data_stream = NULL;
     int data_file_open_flags = O_WRONLY | O_CREAT | O_TRUNC;
     int return_code = -1;
-    char *tmp1;
-
-    /* Write out all the extra data associated with these credentials
-     * support for crypt() added btemko /6/16/00
-     * Please, don't try to free tmp1 - crypt() uses one
-     * static string space, a la getenv()
-     */
-    tmp1=(char *)des_crypt(creds->passphrase,
-	&creds->owner_name[strlen(creds->owner_name)-3]);
-
+
     /*
      * Open with open() first to minimize any race condition with
      * file permissions.
@@ -447,7 +438,6 @@
     }

     fprintf (data_stream, "OWNER=%s\n",creds->owner_name);
-    fprintf (data_stream, "PASSPHRASE=%s\n", tmp1);
     fprintf (data_stream, "LIFETIME=%d\n", creds->lifetime);

     if (creds->credname != NULL)
@@ -593,6 +583,8 @@
             continue;
         }

+	/* We no longer store a PASSPHRASE element.
+	   Read it in for backwards compatibility only. */
         if (strcmp(variable, "PASSPHRASE") == 0)
         {
             creds->passphrase = mystrdup(value);
@@ -692,7 +684,6 @@

     if ((creds == NULL) ||
         (creds->username == NULL) ||
-        (creds->passphrase == NULL) ||
         (creds->owner_name == NULL) ||
         (creds->location == NULL)) {
         verror_put_errno(EINVAL);
@@ -1340,6 +1331,60 @@
     return return_code;
 }

+int
+myproxy_creds_verify_passphrase(const struct myproxy_creds *creds,
+				const char *passphrase)
+{
+    char creds_path[MAXPATHLEN];
+    char data_path[MAXPATHLEN];
+    char lock_path[MAXPATHLEN];
+    char *tmp;
+    int return_code = -1;
+    SSL_CREDENTIALS *ssl_creds = NULL;
+
+    if ((creds == NULL) || (creds->username == NULL) ||
+	(passphrase == NULL)) {
+	verror_put_errno(EINVAL);
+	goto error;
+    }
+
+    if (get_storage_locations(creds->username,
+                              creds_path, sizeof(creds_path),
+                              data_path, sizeof(data_path),
+			      lock_path, sizeof(lock_path),
+			      creds->credname) == -1) {
+        goto error;
+    }
+
+    /*
+     * Verify the passphrase here.
+     * If the private key is encrypted, verify the passphrase by attempting
+     * to decrypt.
+     * Otherwise, if we have a crypted passphrase in the myproxy_creds
+     * struct, verify against that (for backwards compatibility).
+     */
+    if (ssl_private_key_is_encrypted(creds_path) == 1 &&
+	(ssl_creds = ssl_credentials_new()) != NULL &&
+	ssl_private_key_load_from_file(ssl_creds, creds_path, passphrase,
+				       NULL) == SSL_SUCCESS) {
+	return_code = 1;
+    }
+    else if (creds->passphrase &&
+	     strlen(passphrase) >= MIN_PASS_PHRASE_LEN &&
+	     (tmp = (char *)des_crypt(passphrase,
+		   &creds->owner_name[strlen(creds->owner_name)-3])) != NULL &&
+	     strcmp(creds->passphrase, tmp) == 0) {
+	return_code = 1;
+    }
+    else
+	return_code = 0;
+
+  error:
+    ssl_credentials_destroy(ssl_creds);
+
+    return return_code;
+}
+
 void myproxy_creds_free_contents(struct myproxy_creds *creds)
 {
     if (creds == NULL) return;