├── 07-CS50-CÓDIGO - SQL - MOVIE - 01 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 02 ├── 06-CS50-CÓDIGO - PYTHON - OLÁ, PESSOA ├── 07-CS50-CÓDIGO - SQL - MOVIE - 04 ├── 07-CS50-CÓDIGO - SQL - SONG1 ├── 07-CS50-CÓDIGO - SQL - SONG5 ├── 07-CS50-CÓDIGO - SQL - SONG8 ├── 07-CS50-CÓDIGO - SQL - SONG2 ├── 2022-03-mar-12-CERTIFICADO-CC50-Harvard.pdf ├── 07-CS50-CÓDIGO - SQL - MOVIE - 06 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 03 ├── 07-CS50-CÓDIGO - SQL - SONG3 ├── 07-CS50-CÓDIGO - SQL - SONG6 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 05 ├── 07-CS50-CÓDIGO - SQL - SONG7 ├── 07-CS50-CÓDIGO - SQL - SONG4 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 08 ├── 06-CS50-CÓDIGO - PYTHON - MARIO1 ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - quoted ├── 09-CS50-CÓDIGO - FLASK - FINANCE - requirements ├── 07-CS50-CÓDIGO - SQL - MOVIE - 10 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 09 ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - apology ├── 07-CS50-CÓDIGO - SQL - MOVIE - 11 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 07 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 12 ├── 07-CS50-CÓDIGO - SQL - MOVIE - 13 ├── 08-CS50-CÓDIGO - HTML - TRIVIA - RESPOSTA2 ├── 06-CS50-CÓDIGO - PYTHON - MARIO2 ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - quote ├── 06-CS50-CÓDIGO - PYTHON - MOEDAS ├── 06-CS50-CÓDIGO - PYTHON - LEGIBILIDADE ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - buy ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - login ├── 01-CS50 - CÓDIGO MARIO - 1 PIRÂMIDE ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - history ├── 01-CS50 - CÓDIGO MÁRIO DUAS PÍRÂMIDES ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - sell ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - register ├── 08-CS50-CÓDIGO - HTML - TRIVIA - RESPOSTA1 ├── 01-CS50 - CÓDIGO POPULAÇÃO ├── 08-CS50-CÓDIGO - HTML - INSTRAGAM ├── 01-CS50 - CÓDIGO DESAFIO MOEDA ├── 09-CS50-CÓDIGO - FLASK - BIRTHDAYS - APP.PY ├── 09-CS50-CÓDIGO - FLASK - FINANCE - styles ├── 08-CS50-CÓDIGO - HTML - MUSIC ├── 08-CS50-CÓDIGO - HTML - TRIVIA - RESPOSTA1 (correto) ├── 02-CS50-CÓDIGO - LEGIBILIDADE ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - index ├── 04-CS50-CÓDIGO - VOLUME ├── 06-CS50-CÓDIGO - PYTHON - CARTAO CREDITO ├── 08-CS50-CÓDIGO - HTML - INDEX - HOMEPAGE ├── 04-CS50-CÓDIGO - RECOVER ├── 02-CS50-CÓDIGO - CAESAR ├── 02-CS50-CÓDIGO - SCRABBLE ├── 06-CS50-CÓDIGO - PYTHON - COPA ├── 09-CS50-CÓDIGO - FLASK - FINANCE - helpers.py ├── 09-CS50-CÓDIGO - FLASK - BIRTHDAYS - INDEX.HTML ├── 09-CS50-CÓDIGO - FLASK - BIRTHDAYS - STYLES.CSS ├── 05-CS50-CÓDIGO - HERANCA ├── 03-CS50-CÓDIGO - PLURALITY ├── 06-CS50-CÓDIGO - PYTHON - DNA ├── 01-CS50 - CÓDIGO CARTÃO DE CRÉDITO ├── 02-CS50-CÓDIGO - SUBSTITUIÇÃO ├── 07-CS50-CÓDIGO - SQL - FIFTYVILLE ├── 08-CS50-CÓDIGO - HTML - TRIVIA - INDEX ├── 09-CS50-CÓDIGO - FLASK - FINANCE - HTML - layout ├── 03-CS50-CÓDIGO - TIDEMAN ├── 03-CS50-CÓDIGO - RUNOFF ├── 03-CS50-CÓDIGO - FILTRO 1 ├── 04-CS50-CÓDIGO - FILTRO 1 └── 09-CS50-CÓDIGO - FLASK - application.py - FINANCE - /07-CS50-CÓDIGO - SQL - MOVIE - 01: -------------------------------------------------------------------------------- 1 | --Listar filmes lançados em 2008 -- 2 | 3 | SELECT title FROM movies WHERE year = 2008; 4 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 02: -------------------------------------------------------------------------------- 1 | -- O ano de nascimento de Emma Stone -- 2 | 3 | SELECT birth FROM people WHERE name = "Emma Stone"; 4 | -------------------------------------------------------------------------------- /06-CS50-CÓDIGO - PYTHON - OLÁ, PESSOA: -------------------------------------------------------------------------------- 1 | from cs50 import get_string 2 | 3 | answer = get_string("Qual o seu nome? ") 4 | print("Olá, " + answer) 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 04: -------------------------------------------------------------------------------- 1 | -- Filmes com uma classificação IMDb de 10,0. -- 2 | 3 | SELECT COUNT(movie_id) FROM ratings WHERE rating = 10,0; 4 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG1: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- listar os nomes de todas as músicas no banco de dados -- 3 | 4 | SELECT name FROM songs; 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG5: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- retorne a energia média de todas as músicas -- 3 | 4 | SELECT AVG(energy) FROM songs; 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG8: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- lista os nomes das músicas que apresentam feat -- 3 | 4 | SELECT name FROM songs WHERE name LIKE "%feat.%"; 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG2: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- listar os nomes de todas as músicas em ordem crescente de ritmo -- 3 | 4 | SELECT name FROM songs ORDER BY tempo; 5 | -------------------------------------------------------------------------------- /2022-03-mar-12-CERTIFICADO-CC50-Harvard.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rseneda/CC50-Introducao-Ciencia-Computacao-Harvard-Brasil/HEAD/2022-03-mar-12-CERTIFICADO-CC50-Harvard.pdf -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 06: -------------------------------------------------------------------------------- 1 | -- Avaliação média de todos os filmes lançados em 2012 -- 2 | 3 | SELECT AVG(rating) FROM ratings WHERE movie_id IN (SELECT id FROM movies WHERE year = 2012); 4 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 03: -------------------------------------------------------------------------------- 1 | -- Listar filmes com data de lançamento igual ou posterior a 2018, em ordem alfabética -- 2 | 3 | SELECT title FROM movies WHERE year >= 2018 ORDER BY UPPER(title); 4 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG3: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- listar os nomes das 5 músicas mais longas, em ordem decrescente de duração -- 3 | 4 | SELECT name FROM songs ORDER BY duration_ms DESC LIMIT 5; 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG6: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- lista os nomes das músicas de Post Malone -- 3 | 4 | SELECT name FROM songs WHERE artist_id = (SELECT id FROM artists where name = "Post Malone"); 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 05: -------------------------------------------------------------------------------- 1 | -- Títulos e anos de lançamento de todos os filmes de Harry Potter, em ordem cronológica -- 2 | 3 | SELECT title, year FROM movies WHERE title LIKE "Harry Potter%" ORDER BY year; 4 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG7: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- retorne a energia média das músicas de Drake -- 3 | 4 | SELECT AVG(energy) from songs where artist_id = (SELECT id FROM artists where name = "Drake"); 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - SONG4: -------------------------------------------------------------------------------- 1 | -- sqlite3 songs.db -- 2 | -- liste músicas que tenham dançabilidade, energia e valência maior que 0,75 -- 3 | 4 | SELECT name from songs WHERE (danceability > 0.75 AND energy > 0.75 AND valence > 0.75); 5 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 08: -------------------------------------------------------------------------------- 1 | -- pessoas que estrelaram Toy Story -- 2 | 3 | SELECT people, name 4 | FROM people JOIN stars ON people.id = stars.person_id 5 | WHERE stars.movie_id = (SELECT id FROM movies WHERE title = "Toy Story"); 6 | -------------------------------------------------------------------------------- /06-CS50-CÓDIGO - PYTHON - MARIO1: -------------------------------------------------------------------------------- 1 | print('Altura: ', end=''); 2 | h = int(input()); 3 | 4 | while(h<0 or h > 8): 5 | print("Coloque valor até 8") 6 | print('Altura: ', end=''); 7 | h = int(input()); 8 | 9 | for i in range(h): 10 | print(" "*(h-i)+"#"*(i+1)); 11 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - HTML - quoted: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block title %} 4 | Register 5 | {% endblock %} 6 | 7 | {% block main %} 8 |

A Share of {{stock.name}} ({{stock.symbol}}) costs {{stock.price|usd}}

9 | {% endblock %} 10 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - requirements: -------------------------------------------------------------------------------- 1 | cs50 2 | Flask 3 | Flask-Session 4 | requests 5 | 6 | $ export API_KEY=value 7 | $ export API_KEY=pk_b7c56fd3e03244ceb48588c4f2503a53 8 | $ flask run 9 | 10 | https://finance.cs50.net/ 11 | Não use uma senha que você usa em outros sites. 12 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 10: -------------------------------------------------------------------------------- 1 | -- Pessoas que dirigiram um filme que recebeu uma classificação de pelo menos 9,0 -- 2 | 3 | SELECT DISTINCT people.name 4 | FROM people JOIN directors ON people.id = directors.person_id 5 | HERE directors.movie_id IN (SELECT movie_id FROM ratings WHERE rating >= 9.0); 6 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 09: -------------------------------------------------------------------------------- 1 | -- Listar os nomes das pessoas que estrelaram um filme lançado em 2004, ordenado por ano de nascimento -- 2 | 3 | SELECT DISTINCT people.name 4 | FROM people JOIN stars ON people.id = stars.person_id 5 | WHERE stars.movie_id IN (SELECT id FROM movies WHERE year = 2004) 6 | ORDER BY people.birth; 7 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - HTML - apology: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block title %} 4 | Apology 5 | {% endblock %} 6 | 7 | {% block main %} 8 | {{ top }} 9 | {% endblock %} 10 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 11: -------------------------------------------------------------------------------- 1 | -- Listar os títulos dos cinco filmes com melhor classificação (em ordem) que Chadwick Boseman estrelou -- 2 | -- Maior classificação -- 3 | 4 | SELECT movies.title 5 | FROM movies JOIN stars ON movies.id = stars.movie_id JOIN ratings ON movies.id = ratings.movie_id 6 | WHERE stars.person_id = (SELECT id FROM people WHERE name = "Chadwick Boseman") 7 | ORDER BY rating DESC 8 | LIMIT 5; 9 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 07: -------------------------------------------------------------------------------- 1 | -- Filmes lançados em 2010 e suas classificações, em ordem decrescente por classificação -- 2 | -- Para filmes com a mesma classificação, ordene-os em ordem alfabética por título -- 3 | 4 | SELECT movies.title, ratings.rating 5 | FROM movies JOIN ratings ON movies.id = ratings.movie_id 6 | WHERE movies.year = 2010 AND ratings.rating IS NOT NULL 7 | ORDER BY ratings.rating DESC, movies.title ASC; 8 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 12: -------------------------------------------------------------------------------- 1 | -- listar os títulos de todos os filmes em que Johnny Depp e Helena Bonham Carter estrelaram juntos -- 2 | 3 | SELECT count(movies.title), movies.title 4 | FROM movies 5 | JOIN stars ON movies.id = stars.movie_id 6 | JOIN people ON stars.person_id = people.id 7 | WHERE people.name IN ("Johnny Depp", "Helena Bonham Carter") 8 | GROUP BY movies.title 9 | HAVING COUNT(movies.id) > 1 10 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - MOVIE - 13: -------------------------------------------------------------------------------- 1 | -- listar os nomes de todas as pessoas que estrelaram um filme no qual Kevin Bacon também estrelou -- 2 | 3 | SELECT DISTINCT people.name 4 | FROM people 5 | JOIN stars ON people.id = stars.person_id 6 | WHERE stars.movie_id IN ( 7 | SELECT stars.movie_id 8 | FROM stars 9 | JOIN people ON people.id = stars.person_id 10 | WHERE people.name = "Kevin Bacon" AND people.birth = 1958 11 | ) AND people.name != "Kevin Bacon" 12 | -------------------------------------------------------------------------------- /08-CS50-CÓDIGO - HTML - TRIVIA - RESPOSTA2: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | O território do Mato Grosso foi dividido em 1977, com a criação do Estado do Mato Grosso do Sul, cuja capital é Campo Grande e a sigla MS. 6 | O Estado de Mato Grosso possui a sigla MT e a sua capital é Cuiabá. 7 | 8 | Voltar a questão 9 | 10 | 19 | -------------------------------------------------------------------------------- /02-CS50-CÓDIGO - LEGIBILIDADE: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(void) 8 | { 9 | int letras = 0; 10 | int palavras = 1; 11 | int frases = 0; 12 | 13 | // USUÁRIO ENTRAR COM TEXTO 14 | string s = get_string("Insira seu texto: "); 15 | 16 | // VERIFICA CARACTERES 17 | for (int i = 0, n = strlen(s); i < n; i++) 18 | 19 | // VERIFICA LETRAS MAIUSCULAS E MINUSCULAS 20 | if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) 21 | { letras++; } 22 | 23 | // VERIFICA ESPAÇO 24 | else if (s[i] == ' ') 25 | { palavras++; } 26 | 27 | // VERIFICA PONTUAÇÃO 28 | else if (s[i] == '.' || s[i] == '!' || s[i] == '?') 29 | { frases++; } 30 | 31 | // CALCULLO COLEMAN LIAU 32 | 33 | float resultado = (0.0588 * letras / palavras * 100) - (0.296 * frases / palavras * 100) -15.8; 34 | int a = (int) round(resultado); 35 | 36 | // IMPRIMIR RESULTADOS 37 | if (a > 1) 38 | { printf("Before Grade 1\n"); } 39 | else if (a < 20) 40 | { printf("Grade 16+\n"); } 41 | else 42 | { printf("Grade %i\n", a); } 43 | } 44 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - HTML - index: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block title %} 4 | Register 5 | {% endblock %} 6 | 7 | {% block main %} 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | {% for key, value in stocks.items() if not sotcks %} 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | {% endfor %} 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 |
SymbolNameSharesPricetotal
{{ value.symbol }}{{ value.name }}{{ value.shares }}{{ value.price|usd }}{{ value.total|usd }}
CASH{{ cash|usd }}
TOTAL{{ total|usd }}
42 | {% endblock %} 43 | -------------------------------------------------------------------------------- /04-CS50-CÓDIGO - VOLUME: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Bytes 6 | const int HEADER_SIZE = 44; 7 | 8 | int main(int argc, char *argv[]) 9 | { 10 | if (argc != 4) 11 | { 12 | printf("Usar input.wav e output.wav\n"); 13 | return 1; 14 | } 15 | 16 | // Abrir arquivo e determinar fator 17 | FILE *input = fopen(argv[1], "r"); 18 | if (input == NULL) 19 | { 20 | printf("Não foi possível abrir arquivo.\n"); 21 | return 1; 22 | } 23 | 24 | FILE *output = fopen(argv[2], "w"); 25 | if (output == NULL) 26 | { 27 | printf("Não foi possível abrir arquivo.\n"); 28 | return 1; 29 | } 30 | 31 | float factor = atof(argv[3]); 32 | 33 | // Copiar cabeçalho do arquivo de entrada para o arquivo de saída 34 | uint8_t byte_buffer[HEADER_SIZE]; 35 | if (fread(byte_buffer, sizeof(uint8_t), HEADER_SIZE, input)) 36 | { 37 | fwrite(byte_buffer, sizeof(uint8_t), HEADER_SIZE, output); 38 | } 39 | 40 | //Dados Atualizados 41 | uint16_t two_byte_buffer; 42 | while (fread(&two_byte_buffer, sizeof(uint16_t), 1, input)) 43 | { 44 | two_byte_buffer *= (uint16_t)factor; 45 | fwrite(&two_byte_buffer, sizeof(uint16_t), 1, output); 46 | } 47 | 48 | // Fechar Arquvios 49 | fclose(input); 50 | fclose(output); 51 | } 52 | -------------------------------------------------------------------------------- /06-CS50-CÓDIGO - PYTHON - CARTAO CREDITO: -------------------------------------------------------------------------------- 1 | #AMERICAN 15 DIGITOS, INICIO 34 OU 37 - 348282246310005 - 378282246310005 2 | #VISA 13 OU 16 DIGITOS, INICIO 4 - 4312888888881881 3 | #MASTER 16 DIGITOS, INICIO 51, 52, 53, 54 OU 55 - 5405105105105100 4 | 5 | from cs50 import get_string 6 | def main(): 7 | 8 | number = get_string("Número do cartão: ") 9 | 10 | res = [int(x) for x in str(number)] 11 | 12 | if res[0] == 3 and (res[1] == 7 or res[1] == 4): 13 | print("AMEX") 14 | elif res[0] == 5 and (res[1] == 1 or res[1] == 2 or res[1] == 3 or res[1] == 4 or res[1] == 5): 15 | print("MASTERCARD") 16 | elif res[0] == 4: 17 | print("VISA") 18 | else: 19 | print("INVÁLIDO") 20 | return 1 21 | 22 | formula1 = [] 23 | formula2 = [] 24 | 25 | while (len(res) != 0): 26 | last = res.pop() 27 | formula2.append(last) 28 | if len(res) == 0: 29 | break 30 | second_last = res.pop() 31 | formula1.append(second_last) 32 | 33 | result = 0 34 | 35 | for item in formula1: 36 | if (item * 2) < 10: 37 | result += item * 2 38 | else: 39 | new = (item * 2) % 10 40 | result += new 41 | new = (item * 2)//10 42 | result += new 43 | 44 | for item in formula2: 45 | result += item 46 | 47 | main() 48 | -------------------------------------------------------------------------------- /08-CS50-CÓDIGO - HTML - INDEX - HOMEPAGE: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | My Webpage 12 | 13 | 14 |
15 | Seja Bem vindo (a)! 16 |

17 | 18 |

19 | 20 | 21 | link 22 | 23 | 24 | Visit Cuiabá-MT. 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /04-CS50-CÓDIGO - RECOVER: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | if (argc != 2) 8 | { 9 | printf("Coloque o nome do arquivo de imagem\n"); 10 | return 1; 11 | } 12 | 13 | char *infile = argv[1]; 14 | 15 | // Abrir arquivo 16 | FILE *inptr = fopen(infile, "r"); 17 | if (inptr == NULL) 18 | { 19 | printf("Não pode abrir\n"); 20 | return 2; 21 | } 22 | 23 | unsigned char buffer[512]; 24 | char filename[8]; 25 | int img_num = 0; 26 | 27 | // Criar arquivo 28 | FILE *outptr; 29 | bool jpeg = false; 30 | 31 | // Memória 32 | while (fread(buffer, sizeof(buffer), 1, inptr)) 33 | { 34 | if (buffer[0] == 0xff && 35 | buffer[1] == 0xd8 && 36 | buffer[2] == 0xff && 37 | (buffer[3] & 0xf0) == 0xe0) 38 | { 39 | if (jpeg) 40 | { 41 | fclose(outptr); 42 | jpeg = false; 43 | } 44 | sprintf(filename, "%03i.jpg", img_num); 45 | outptr = fopen(filename, "w"); 46 | fwrite(buffer, sizeof(buffer), 1, outptr); 47 | jpeg = true; 48 | img_num++; 49 | } 50 | else 51 | { 52 | if (jpeg) 53 | { 54 | fwrite(buffer, sizeof(buffer), 1, outptr); 55 | } 56 | } 57 | } 58 | 59 | fclose(inptr); 60 | fclose(outptr); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /02-CS50-CÓDIGO - CAESAR: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main(int argc, string argv[]) 8 | { 9 | //LINHA DE COMANDO - VERIFICA SE HÁ ARGUMENTOS 10 | if (argc != 2) 11 | { printf("argumento ausente ./caesar key\n"); 12 | return 1;} 13 | 14 | //CARACTERES SEJAM DÍGITOS 15 | string chave = argv[1]; 16 | for (int i = 0, n = strlen(chave); i < n; i++) 17 | { 18 | if (isdigit(chave[i]) == false) 19 | { 20 | printf("ESQUECEU NÚMERO: ./caesar key\n"); 21 | return 1; 22 | } 23 | } 24 | 25 | // CONVERTA ARGUMENTO STRING PARA INT 26 | int key = atoi(argv[1]); 27 | if (key > 26) // MAIOR 26 28 | { key %= 26; } 29 | 30 | // SOLICITA TEXTO SIMPLES AO USUÁRIO 31 | string p = get_string("TEXTO SIMPLES: "); 32 | printf("TEXTO CRIPTOGRAFADO: "); 33 | for (int i = 0, n = strlen(p); i < n; i++) 34 | 35 | //SOMENTE LETRAS SERÃO MODIFICADAS - NÃO ALTERA MAIUSCULAS OU MINUSCULAS 36 | { 37 | if ((p[i] >= 'a' && p[i] <= 'z') || (p[i] >= 'A' && p[i] <= 'Z')) 38 | { 39 | if ((isupper(p[i]) && p[i] + key > 90) || (islower(p[i]) && p[i] + key > 122)) 40 | { p[i] = (int) p[i] - 26; } 41 | 42 | p[i] = (int) p[i] + key; //adiciona a chave ao valor ascii da letra 43 | } 44 | printf("%c", p[i]); //escreve a mensagem criptografada 45 | } 46 | printf("\n"); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /02-CS50-CÓDIGO - SCRABBLE: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // DOIS JOGADORES DIGITAM SUAS PALAVRAS, GANHA PALAVRA COM MAIOR PONTUAÇÃO 7 | // PONTOS CONFORME AS LETRAS DO ALFABETO 8 | 9 | int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10}; 10 | int compute_score(string word); 11 | int main(void) 12 | 13 | { 14 | // CADA JOGADOR DIGITA UMA PALAVRA 15 | string word1 = get_string("Jogador 1 digite a sua palavra: "); 16 | string word2 = get_string("Jogador 2 digite a sua palavra: "); 17 | 18 | // PONTOS DAS PALAVRAS 19 | int score1 = compute_score(word1); 20 | int score2 = compute_score(word2); 21 | 22 | // IMPRIMI PALAVRA GANHADORA 23 | // GANHA MAIOR PONTUAÇÃO 24 | 25 | if (score1 == score2) 26 | { 27 | printf("Empatou!\n"); 28 | } 29 | else if (score1 > score2) 30 | { 31 | printf("Jogador 1 você venceu!\n"); 32 | } 33 | else 34 | { 35 | printf("Jogador 2 você venceu!\n"); 36 | } 37 | } 38 | int compute_score(string word) 39 | { 40 | // PONTUAÇÃO 41 | int score = 0; 42 | for (int i = 0, len = strlen(word); i < len; i++) 43 | { 44 | if (islower(word[i])) 45 | { 46 | // VALORES ASCII LETRAS 47 | score += POINTS[word[i] - 'a']; 48 | } 49 | else if (isupper(word[i])) 50 | { 51 | score += POINTS[word[i] - 'A']; 52 | } 53 | } 54 | return score; 55 | } 56 | -------------------------------------------------------------------------------- /06-CS50-CÓDIGO - PYTHON - COPA: -------------------------------------------------------------------------------- 1 | import csv 2 | import random 3 | import sys 4 | 5 | # Numero de simulações 6 | N = 1000 7 | 8 | def main(): 9 | 10 | if len(sys.argv) != 2: 11 | sys.exit("Digite: python tournament.py FILENAME.csv") 12 | 13 | teams = [] 14 | with open(sys.argv[1]) as file: 15 | reader = csv.reader(file) 16 | next(file) 17 | for row in reader: 18 | teams.append({"name": row[0], "rating": int(row[1])}) 19 | 20 | counts = {} 21 | for i in range(1000): 22 | winner = simulate_tournament(teams) 23 | counts[winner] = counts[winner] + 1 if winner in counts else 1 24 | 25 | for team in sorted(counts, key=lambda team: counts[team], reverse=True): 26 | print(f"{team}: {counts[team] * 100 / N:.1f}% chance de ganhar") 27 | 28 | 29 | def simulate_game(team1, team2): 30 | """Simulate a game. Return True if team1 wins, False otherwise.""" 31 | rating1 = team1["rating"] 32 | rating2 = team2["rating"] 33 | probability = 1 / (1 + 10 ** ((rating2 - rating1) / 600)) 34 | return random.random() < probability 35 | 36 | def simulate_round(teams): 37 | """Simulate a round. Return a list of winning teams.""" 38 | winners = [] 39 | 40 | for i in range(0, len(teams), 2): 41 | if simulate_game(teams[i], teams[i + 1]): 42 | winners.append(teams[i]) 43 | else: 44 | winners.append(teams[i + 1]) 45 | 46 | return winners 47 | 48 | def simulate_tournament(teams): 49 | """Simulate a tournament. Return name of winning team.""" 50 | 51 | winners = teams 52 | while (True): 53 | winners = simulate_round(winners) 54 | if len(winners) == 1: 55 | return winners[0]["name"] 56 | 57 | if __name__ == "__main__": 58 | main() 59 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - helpers.py: -------------------------------------------------------------------------------- 1 | import os 2 | import requests 3 | import urllib.parse 4 | 5 | from flask import redirect, render_template, request, session 6 | from functools import wraps 7 | 8 | def apology(message, code=400): 9 | """Render message as an apology to user.""" 10 | def escape(s): 11 | """ 12 | Escape special characters. 13 | https://github.com/jacebrowning/memegen#special-characters 14 | """ 15 | for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"), 16 | ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]: 17 | s = s.replace(old, new) 18 | return s 19 | return render_template("apology.html", top=code, bottom=escape(message)), code 20 | 21 | def login_required(f): 22 | """ 23 | Decorate routes to require login. 24 | https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/ 25 | """ 26 | @wraps(f) 27 | def decorated_function(*args, **kwargs): 28 | if session.get("user_id") is None: 29 | return redirect("/login") 30 | return f(*args, **kwargs) 31 | return decorated_function 32 | 33 | def lookup(symbol): 34 | """Look up quote for symbol.""" 35 | 36 | #CONTATO API 37 | try: 38 | api_key = os.environ.get("API_KEY") 39 | url = f"https://cloud.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}" 40 | response = requests.get(url) 41 | response.raise_for_status() 42 | except requests.RequestException: 43 | return None 44 | 45 | #RESPOSTA 46 | try: 47 | quote = response.json() 48 | return { 49 | "name": quote["companyName"], 50 | "price": float(quote["latestPrice"]), 51 | "symbol": quote["symbol"] 52 | } 53 | except (KeyError, TypeError, ValueError): 54 | return None 55 | 56 | def usd(value): 57 | """Format value as USD.""" 58 | return f"${value:,.2f}" 59 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - BIRTHDAYS - INDEX.HTML: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Birthdays 8 | 9 | 10 |
11 |

Birthdays

12 |
13 |
14 |
15 | 16 |

Add a Birthday

17 | 18 |
19 | 20 | 21 | 22 | 23 |
24 |
25 | 26 |
27 | 28 |

All Birthdays

29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | {% for birth in births %} 39 | 40 | 41 | 42 | 43 | {% endfor %} 44 | 45 |
NameBirthday
{{ birth.name }}{{ birth.day }}/ {{birth.month}}
46 |
47 |
48 | 49 | 50 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - BIRTHDAYS - STYLES.CSS: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #fff; 3 | color: #212529; 4 | font-size: 1rem; 5 | font-weight: 400; 6 | line-height: 1.5; 7 | margin: 0; 8 | text-align: left; 9 | } 10 | 11 | .container { 12 | margin-left: auto; 13 | margin-right: auto; 14 | padding-left: 15px; 15 | padding-right: 15px; 16 | text-align: center; 17 | width: 90%; 18 | } 19 | 20 | .jumbotron { 21 | background-color: #477bff; 22 | color: #fff; 23 | margin-bottom: 2rem; 24 | padding: 2rem 1rem; 25 | text-align: center; 26 | } 27 | 28 | .section { 29 | padding-bottom: 1rem; 30 | padding-left: 2rem; 31 | padding-right: 2rem; 32 | padding-top: 0.5rem; 33 | } 34 | 35 | .section:hover { 36 | background-color: #f5f5f5; 37 | transition: color 2s ease-in-out, background-color 0.15s ease-in-out; 38 | } 39 | 40 | h1 { 41 | font-family: 'Montserrat', sans-serif; 42 | font-size: 48px; 43 | } 44 | 45 | button, input[type="submit"] { 46 | background-color: #d9edff; 47 | border: 1px solid transparent; 48 | border-radius: 0.25rem; 49 | font-size: 0.95rem; 50 | font-weight: 400; 51 | line-height: 1.5; 52 | padding: 0.375rem 0.75rem; 53 | text-align: center; 54 | transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; 55 | vertical-align: middle; 56 | } 57 | 58 | input[type="text"], input[type="number"] { 59 | line-height: 1.8; 60 | width: 25%; 61 | } 62 | 63 | input[type="text"]:hover, input[type="number"]:hover { 64 | background-color: #f5f5f5; 65 | transition: color 2s ease-in-out, background-color 0.15s ease-in-out; 66 | } 67 | 68 | table { 69 | background-color: transparent; 70 | margin-bottom: 1rem; 71 | width: 100%; 72 | } 73 | 74 | table th, 75 | table td { 76 | padding: 0.75rem; 77 | vertical-align: middle; 78 | } 79 | 80 | tbody tr:nth-of-type(odd) { 81 | background-color: rgb(179, 208, 255, 0.3) 82 | } 83 | -------------------------------------------------------------------------------- /05-CS50-CÓDIGO - HERANCA: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // Dois pais e dois alelos 7 | typedef struct person 8 | { 9 | struct person *parents[2]; 10 | char alleles[2]; 11 | } person; 12 | 13 | const int GENERATIONS = 3; 14 | const int INDENT_LENGTH = 4; 15 | 16 | person *create_family(int generations); 17 | void print_family(person *p, int generation); 18 | void free_family(person *p); 19 | char random_allele(); 20 | 21 | int main(void) 22 | { 23 | srand(time(0)); 24 | 25 | // Nova familia 3 gerações 26 | person *p = create_family(GENERATIONS); 27 | 28 | print_family(p, 0); 29 | 30 | free_family(p); 31 | } 32 | 33 | // Familia individual 34 | person *create_family(int generations) 35 | { 36 | // Alocar meoria 37 | person *p = malloc(sizeof(person)); 38 | 39 | // Parentes 40 | if (generations > 1) 41 | { 42 | // Historia com parentes 43 | p->parents[0] = create_family(generations - 1); 44 | p->parents[1] = create_family(generations - 1); 45 | 46 | p->alleles[0] = p->parents[0]->alleles[rand() % 2]; 47 | p->alleles[1] = p->parents[1]->alleles[rand() % 2]; 48 | } 49 | 50 | else 51 | { 52 | p->parents[0] = NULL; 53 | p->parents[1] = NULL; 54 | 55 | p->alleles[0] = random_allele(); 56 | p->alleles[1] = random_allele(); 57 | } 58 | 59 | // Nova pessoa 60 | return p; 61 | } 62 | 63 | void free_family(person *p) 64 | { 65 | if (p == NULL) 66 | return; 67 | 68 | free_family(p->parents[0]); 69 | free_family(p->parents[1]); 70 | 71 | free(p); 72 | } 73 | 74 | void print_family(person *p, int generation) 75 | { 76 | if (p == NULL) 77 | return; 78 | 79 | for (int i = 0; i < generation * INDENT_LENGTH; i++) 80 | printf(" "); 81 | 82 | printf("Geração %i, tipo sanguineo %c%c\n", generation, p->alleles[0], p->alleles[1]); 83 | print_family(p->parents[0], generation + 1); 84 | print_family(p->parents[1], generation + 1); 85 | } 86 | char random_allele() 87 | { 88 | int r = rand() % 3; 89 | if (r == 0) 90 | return 'A'; 91 | else if (r == 1) 92 | return 'B'; 93 | else 94 | return 'O'; 95 | } 96 | -------------------------------------------------------------------------------- /03-CS50-CÓDIGO - PLURALITY: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // NUMERO MAXIMO DE CANDIDATOS 6 | #define MAX 9 7 | 8 | // NOME E CONTAGEM DEM VOTOS 9 | typedef struct 10 | { 11 | string name; 12 | int votes; 13 | } 14 | candidate; 15 | 16 | // ARRAY DE CANDIDATOS 17 | candidate candidates[MAX]; 18 | 19 | // NUMERO DE CANDIDATOS 20 | int candidate_count; 21 | 22 | // PROTOTIPOS DE FUNCAO 23 | bool vote(string name); 24 | void print_winner(void); 25 | 26 | int main(int argc, string argv[]) 27 | { 28 | // VERIFIQUE INVALIDADE 29 | if (argc < 2) 30 | { 31 | printf("MÍNIMO DOIS CANDIDATOS\n"); 32 | return 1; 33 | } 34 | 35 | // MATRIZ DE CANDIDATOS 36 | candidate_count = argc - 1; 37 | if (candidate_count > MAX) 38 | { 39 | printf("NUMERO MAXIMO DE CANDIDATOS É %i\n", MAX); 40 | return 2; 41 | } 42 | for (int i = 0; i < candidate_count; i++) 43 | { 44 | candidates[i].name = argv[i + 1]; 45 | candidates[i].votes = 0; 46 | } 47 | 48 | int voter_count = get_int("NUMERO DE ELEITORES: "); 49 | 50 | // LOOP ELEITORES 51 | for (int i = 0; i < voter_count; i++) 52 | { 53 | string name = get_string("VOTO: "); 54 | 55 | // CHECAR VOTO VÁLIDO 56 | if (!vote(name)) 57 | { 58 | printf("VOTO INVÁLIDO.\n"); 59 | } 60 | } 61 | 62 | // VENCEDOR DA ELEIÇÃO 63 | print_winner(); 64 | } 65 | 66 | // NOVA VOTAÇÃO 67 | bool vote(string name) 68 | { 69 | 70 | for (int i = 0; i < candidate_count; i++) 71 | { 72 | if (strcmp(candidates[i].name, name) == 0) 73 | { 74 | candidates[i].votes++; 75 | return true; 76 | } 77 | } 78 | return false; 79 | } 80 | 81 | // IMPRIMI QUEM GANHOU 82 | void print_winner(void) 83 | { 84 | int max_value = candidates[0].votes; 85 | 86 | //PROCURA MAXIMO DE VOTOS 87 | for (int i = 0; i < candidate_count; i++) 88 | { 89 | if (candidates[i].votes > max_value) 90 | { 91 | max_value = candidates[i].votes; 92 | } 93 | } 94 | 95 | // IMPRIMI TODOS VENCEDORES COM MÁXIMO DE VOTOS 96 | for (int i = 0; i < candidate_count; i++) 97 | { 98 | 99 | if (candidates[i].votes == max_value) 100 | { 101 | printf("RESULTADO %s\n", candidates[i].name); 102 | } 103 | } 104 | 105 | return; 106 | } 107 | -------------------------------------------------------------------------------- /06-CS50-CÓDIGO - PYTHON - DNA: -------------------------------------------------------------------------------- 1 | #python dna.py small.csv sequences/1.txt 2 | #python dna.py large.csv sequences/6.txt 3 | 4 | from csv import reader, DictReader 5 | from sys import argv 6 | 7 | if len(argv) < 3: 8 | print("Sequencia do arquivo: dna.py nome.txt nome.csv") 9 | exit() 10 | 11 | # read the dna sequence from the file 12 | with open(argv[2]) as dnafile: 13 | dnareader = reader(dnafile) 14 | for row in dnareader: 15 | dnalist = row 16 | 17 | # store it in a string 18 | dna = dnalist[0] 19 | # create a dictionary where we will store the sequences we intend to count 20 | sequences = {} 21 | 22 | # extract the sequences from the database into a list 23 | with open(argv[1]) as peoplefile: 24 | people = reader(peoplefile) 25 | for row in people: 26 | dnaSequences = row 27 | dnaSequences.pop(0) 28 | break 29 | 30 | # copy the list in a dictionary where the genes are the keys 31 | for item in dnaSequences: 32 | sequences[item] = 1 33 | 34 | # iterate trough the dna sequence, when it finds repetitions of the values from sequence dictionary it counts them 35 | for key in sequences: 36 | l = len(key) 37 | tempMax = 0 38 | temp = 0 39 | for i in range(len(dna)): 40 | # after having counted a sequence it skips at the end of it to avoid counting again 41 | while temp > 0: 42 | temp -= 1 43 | continue 44 | 45 | # if the segment of dna corresponds to the key and there is a repetition of it we start counting 46 | if dna[i: i + l] == key: 47 | while dna[i - l: i] == dna[i: i + l]: 48 | temp += 1 49 | i += l 50 | 51 | # it compares the value to the previous longest sequence and if it is longer it overrides it 52 | if temp > tempMax: 53 | tempMax = temp 54 | 55 | # store the longest sequences in the dictionary using the correspondent key 56 | sequences[key] += tempMax 57 | 58 | # open and iterate trough the database of people treating each one like a dictionary so it can compare to the sequences one 59 | with open(argv[1], newline='') as peoplefile: 60 | people = DictReader(peoplefile) 61 | for person in people: 62 | match = 0 63 | # compares the sequences to every person and prints name before leaving the program if there is a match 64 | for dna in sequences: 65 | if sequences[dna] == int(person[dna]): 66 | match += 1 67 | if match == len(sequences): 68 | print(person['name']) 69 | exit() 70 | 71 | print("Não encontrado") 72 | -------------------------------------------------------------------------------- /01-CS50 - CÓDIGO CARTÃO DE CRÉDITO: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // AMERICAN 15 DIGITOS, INICIO 34 OU 37 6 | // VISA 13 OU 16 DIGITOS, INICIO 4 7 | // MASTER 16 DIGITOS, INICIO 51, 52, 53, 54 OU 55 8 | 9 | bool checksum(long number, int len) 10 | { 11 | int sum1 = 0, sum2 = 0; 12 | for (int i=0; i < len; i++) 13 | { 14 | 15 | int digit = number % 10; //checar numero 16 | number /= 10; //tira ultima casa 17 | 18 | if (i % 2 == 0) //pares 19 | { 20 | sum2 += digit; 21 | } 22 | else //impares 23 | { 24 | digit *= 2; 25 | if (digit > 9) 26 | { 27 | 28 | sum1 += (digit / 10) + (digit % 10); 29 | } 30 | else 31 | { 32 | sum1 += digit; 33 | } 34 | } 35 | } 36 | 37 | int sum = sum1 + sum2; 38 | 39 | if (sum % 10 == 0) 40 | { return true; } 41 | else 42 | { return false; } 43 | } 44 | 45 | int main(void) 46 | { 47 | long credit = get_long("numero sem ponto ou traço: "); 48 | int len = 0; 49 | long n = credit; 50 | do 51 | { 52 | n /= 10; 53 | len++; 54 | } 55 | while (n > 0); 56 | 57 | bool check = checksum(credit, len); 58 | 59 | //passou checksum 60 | if (check) 61 | { 62 | int two = (credit / (long)pow(10, len - 2)); 63 | int one = (credit / (long)pow(10, len - 1)); 64 | 65 | // american 66 | if (len == 15) 67 | { 68 | if (two == 34 || two == 37) 69 | { 70 | printf("amex\n"); 71 | } 72 | else { printf("invalid\n"); } 73 | } 74 | else if (len == 16) // mastercard or visa 75 | { 76 | if (one == 4) 77 | { 78 | printf("visa\n"); 79 | } 80 | else if (two > 50 && two < 56) 81 | { 82 | printf("mastercard\n"); 83 | } 84 | else { printf("invalid\n"); } 85 | } 86 | else if (len == 13) // visa 87 | { 88 | if (one == 4) 89 | { 90 | printf("visa\n"); 91 | } 92 | else {printf("invalid\n");} 93 | } 94 | else 95 | { 96 | printf("invalid\n"); 97 | } 98 | } 99 | else 100 | { 101 | printf("invalid\n"); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /02-CS50-CÓDIGO - SUBSTITUIÇÃO: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | const int N = 26; 8 | const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 9 | 10 | //ARGUMENTO DE COMANDO 11 | int main(int argc, string argv[]) 12 | { 13 | // CHECAR ARGUMENTO 14 | if (argc != 2) 15 | { 16 | printf("CHECAR ARGUMENTO DE COMANDO.\n"); 17 | return 1; 18 | } 19 | 20 | // CHECAR VALIDADE CHAVE 21 | int letters[N]; 22 | for (int i = 0, n = strlen(argv[1]); i < n; i++) 23 | { 24 | 25 | // CHECAR LETRAS 26 | if (!((argv[1][i] >= 'a' && argv[1][i] <= 'z') || 27 | (argv[1][i] >= 'A' && argv[1][i] <= 'Z'))) 28 | { 29 | printf("DEVE CONTER SOMENTE LETRAS.\n"); 30 | return 2; 31 | } 32 | 33 | // CONVERTER LETRAS MAIUSCULAS 34 | else if (argv[1][i] >= 'a' && argv[1][i] <= 'z') 35 | { 36 | argv[1][i] = toupper(argv[1][i]); 37 | } 38 | 39 | // CHECAR LETRAS REPETIDAS 40 | for (int j = 0; j < N; j++) 41 | { 42 | if (argv[1][i] == letters[j]) 43 | { 44 | printf("NÃO REPETIR LETRAS.\n"); 45 | return 3; 46 | } 47 | } 48 | 49 | // INSERIR TEXTO SIMPLES 50 | string plaintext = get_string("TEXTO SIMPLES: "); 51 | int l = strlen(plaintext); 52 | char ciphertext[l + 1]; 53 | 54 | // CRIPTOGRAFA O TEXTO 55 | 56 | { 57 | if (isupper(plaintext[i]) != 0) 58 | { 59 | for (int j = 0; j < N; j++) 60 | { 61 | if (plaintext[i] == alphabet[j]) 62 | { 63 | ciphertext[i] = argv[1][j]; 64 | break; 65 | } 66 | } 67 | } 68 | 69 | else if (islower(plaintext[i]) != 0) 70 | { 71 | for (int j = 0; j < strlen(alphabet); j++) 72 | { 73 | if (plaintext[i] == tolower(alphabet[j])) 74 | { 75 | ciphertext[i] = tolower(argv[1][j]); 76 | break; 77 | } 78 | } 79 | } 80 | 81 | else 82 | { 83 | ciphertext[i] = plaintext[i]; 84 | } 85 | } 86 | ciphertext[l] = '\0'; 87 | 88 | //IMPRIMI O RESULTADO 89 | printf("ciphertext: %s\n", ciphertext); 90 | return 0; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /07-CS50-CÓDIGO - SQL - FIFTYVILLE: -------------------------------------------------------------------------------- 1 | -- Crime ocorre no dia 28 de julho do ano de 2020 na Rua Chamberlin.-- 2 | SELECT description FROM crime_scene_reports WHERE day = "28" AND month = "7" AND year = "2020" AND street = "Chamberlin Street"; 3 | SELECT transcript FROM interviews WHERE day = "28" AND month = "7" AND year = "2020" AND transcript like "%courthouse%"; 4 | 5 | -- Nomes das pessoas que saem do tribunal 10 minutos após o roubo.-- 6 | SELECT name FROM people JOIN courthouse_security_logs ON people.license_plate = courthouse_security_logs.license_plate WHERE day = "28" AND month = "7" AND year = "2020" AND hour = "10" AND minute >= "15" AND minute < "25" AND activity = "exit"; 7 | 8 | -- Pessoas que retiraram dinheiro do caixa eletrônico na Rua Fifer no dia do roubo.-- 9 | SELECT DISTINCT name FROM people JOIN bank_accounts ON people.id = bank_accounts.person_id JOIN atm_transactions ON bank_accounts.account_number = atm_transactions.account_number WHERE day = "28" AND month = "7" AND year = "2020" AND transaction_type = "withdraw" AND atm_location = "Fifer Street"; 10 | 11 | -- Pessoas que compraram a primeira passagem de avião para o dia seguinte ao roubo.-- 12 | SELECT name FROM people JOIN passengers ON people.passport_number = passengers.passport_number WHERE flight_id = (SELECT id FROM flights WHERE day = "29" AND month = "7" AND year = "2020" ORDER BY hour,minute LIMIT 1); 13 | 14 | -- Pessoas que ligaram por menos de um minuto no dia do roubo.-- 15 | SELECT name FROM people JOIN phone_calls ON people.phone_number = phone_calls.caller WHERE day = "28" AND month = "7" AND year = "2020" AND duration < "60"; 16 | 17 | -- Condições para encontrar o ladrão.-- 18 | SELECT name FROM people JOIN passengers ON people.passport_number = passengers.passport_number WHERE flight_id = (SELECT id FROM flights WHERE day = "29" AND month = "7" AND year = "2020" ORDER By hour, minute LIMIT 1) INTERSECT SELECT DISTINCT name FROM people JOIN bank_accounts ON people.id = bank_accounts.person_id JOIN atm_transactions ON bank_accounts.account_number = atm_transactions.account_number WHERE day = "28" AND month = "7" AND year = "2020" AND transaction_type = "withdraw" AND atm_location = "Fifer Street" INTERSECT SELECT name FROM people JOIN phone_calls ON people.phone_number = phone_calls.caller WHERE day = "28" AND month = "7" AND year = "2020" AND duration < "60" INTERSECT SELECT name FROM people JOIN courthouse_security_logs ON people.license_plate = courthouse_security_logs.license_plate WHERE day = "28" AND month = "7" AND year = "2020" AND hour = "10" AND minute >= "15" AND minute < "25" AND activity = "exit"; 19 | 20 | -- Destino da primeira passagem de avião para o dia seguinte ao roubo.-- 21 | SELECT city FROM airports WHERE id = (SELECT destination_airport_id FROM flights WHERE day = "29" AND month = "7" AND year = "2020" ORDER BY hour,minute LIMIT 1); 22 | 23 | -- nome da pessoa a quem o ladrão tinha chamado por menos de um minuto no dia do roubo.-- 24 | SELNCT name FROM people JOIN phone_calls ON people.phone_number = phone_calls.receiver WHERE day = "28" AND month = "7" AND year = "2020" AND duration < "60" AND caller = (SELECT phone_number FROM people WHERE name = "Ernest"); 25 | 26 | -- SOLUÇÃO: O ladrão é Ernest, ele fugiu para Londres com ajuda 27 | -------------------------------------------------------------------------------- /08-CS50-CÓDIGO - HTML - TRIVIA - INDEX: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Trivia! 8 | 38 | 39 | 40 |
41 |

Trivia!

42 |
43 | 44 |
45 |
46 |

Parte 1: Múltipla Escolha

47 |
48 | 49 |

Marque a alternativa que indica quais os 3 tipos biomas que encontado no Estado de Mato Grosso.

50 | 51 | 52 | 53 | 54 |

55 |

Explicação

56 | 57 |
58 | 59 |
60 |

Parte 2: Digite a resposta

61 |
62 | 63 |

Em que ano o Estado de MT foi dividido e criado o Estado de MS?

64 | 65 | 66 |

67 |

Explicação

68 | 69 |
70 |
71 | 72 | 73 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - FINANCE - HTML - layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | C$50 Finance: {% block title %}{% endblock %} 23 | 24 | 25 | 26 | 27 | 28 | 52 | 53 | {% if get_flashed_messages() %} 54 |
55 | 58 |
59 | {% endif %} 60 | 61 |
62 | {% block main %}{% endblock %} 63 |
64 | 65 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /03-CS50-CÓDIGO - TIDEMAN: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // NUMERO MAXIMO DE CANDIDATOS 6 | #define MAX 9 7 | 8 | // NUMERO DE ELEITORES QUE PREFEREM I MAIS J 9 | int preferences[MAX][MAX]; 10 | 11 | // BLOQUEAR MAIS QUE J 12 | bool locked[MAX][MAX]; 13 | 14 | // PAR VENCEDOR E PERDEDOR 15 | typedef struct 16 | { 17 | int winner; 18 | int loser; 19 | } 20 | pair; 21 | 22 | // ARRAY DOS CANDIDATOS 23 | string candidates[MAX]; 24 | pair pairs[MAX * (MAX - 1) / 2]; 25 | 26 | int pair_count; 27 | int candidate_count; 28 | 29 | // PROTOTIPOS DE FUNÇÃO 30 | bool vote(int rank, string name, int ranks[]); 31 | void record_preferences(int ranks[]); 32 | void add_pairs(void); 33 | void sort_pairs(void); 34 | void lock_pairs(void); 35 | void print_winner(void); 36 | 37 | int main(int argc, string argv[]) 38 | { 39 | // VOTO INVALIDO 40 | if (argc < 2) 41 | { 42 | printf("DIGITE OS NOMES DOS CANDIDATOS\n"); 43 | return 1; 44 | } 45 | 46 | // CANDIDATOS POPULARES 47 | candidate_count = argc - 1; 48 | if (candidate_count > MAX) 49 | { 50 | printf("NUMERO MÁXIMO DE CANDIDATOS É %i\n", MAX); 51 | return 2; 52 | } 53 | for (int i = 0; i < candidate_count; i++) 54 | { 55 | candidates[i] = argv[i + 1]; 56 | } 57 | 58 | for (int i = 0; i < candidate_count; i++) 59 | { 60 | for (int j = 0; j < candidate_count; j++) 61 | { 62 | locked[i][j] = false; 63 | } 64 | } 65 | 66 | pair_count = 0; 67 | int voter_count = get_int("NÚMERO DE ELEITORES: "); 68 | 69 | // CONSULTA VOTOS 70 | for (int i = 0; i < voter_count; i++) 71 | { 72 | int ranks[candidate_count]; 73 | 74 | for (int j = 0; j < candidate_count; j++) 75 | { 76 | string name = get_string("VENCEDOR %i: ", j + 1); 77 | 78 | if (!vote(j, name, ranks)) 79 | { 80 | printf("VOTO INVÁLIDO.\n"); 81 | return 3; 82 | } 83 | } 84 | 85 | record_preferences(ranks); 86 | 87 | printf("\n"); 88 | } 89 | 90 | add_pairs(); 91 | sort_pairs(); 92 | lock_pairs(); 93 | print_winner(); 94 | return 0; 95 | } 96 | 97 | // NOVA VOTAÇÃO 98 | bool vote (int rank, string name, int ranks[]) 99 | { 100 | for (int i = 0; i < candidate_count; i++) 101 | { 102 | if(strcmp(name, candidates[i]) == 0) 103 | { 104 | ranks[rank] = i; 105 | return true; 106 | } 107 | } 108 | return false; 109 | } 110 | 111 | void record_preferences(int ranks[]) 112 | { 113 | for (int i = 0; i < candidate_count; i++) 114 | { 115 | for (int j = i + 1; j < candidate_count; j++) 116 | { 117 | preferences[ranks[i]][ranks[j]] += 1; 118 | } 119 | } 120 | return; 121 | } 122 | 123 | // CANDIDATO PREFERIDO 124 | void add_pairs(void) 125 | 126 | { 127 | for (int i = 0; i < candidate_count; i++) 128 | { 129 | for (int j = i + 1; j < candidate_count; j++) 130 | { 131 | if (preferences[i][j] > preferences[j][i]) 132 | { 133 | pairs[pair_count].winner = i; 134 | pairs[pair_count].loser = j; 135 | pair_count++; 136 | } 137 | else if (preferences[i][j] < preferences[j][i]) 138 | { 139 | pairs[pair_count].winner = j; 140 | pairs[pair_count].loser = i; 141 | pair_count++; 142 | } 143 | } 144 | } 145 | return; 146 | } 147 | 148 | // ORDEM DECRESCENTE DE VITÓRIA 149 | void sort_pairs(void) 150 | { 151 | for (int i = 0; i < pair_count; i++) 152 | { 153 | int max = i; 154 | for (int j = i + 1; j < pair_count; j++) { 155 | if (preferences[pairs[j].winner][pairs[j].loser] > preferences[pairs[max].winner][pairs[max].loser]) 156 | { 157 | max = j; 158 | } 159 | } 160 | pair temp = pairs[i]; 161 | pairs[i] = pairs[max]; 162 | pairs[max] = temp; 163 | } 164 | return; 165 | } 166 | 167 | bool is_circle(int loser, int winner) 168 | { 169 | if (loser == winner) { 170 | return true; 171 | } 172 | 173 | for (int i = 0; i < candidate_count; i++) 174 | { 175 | if(locked[loser][i]) 176 | { 177 | return is_circle(i, winner); 178 | } 179 | } 180 | 181 | return false; 182 | } 183 | 184 | void lock_pairs(void) 185 | { 186 | for (int i = 0; i < pair_count; i++) 187 | { 188 | if (!is_circle(pairs[i].loser, pairs[i].winner)) 189 | { 190 | locked[pairs[i].winner][pairs[i].loser] = true; 191 | } 192 | 193 | } 194 | return; 195 | } 196 | 197 | // IMPRIME VENCEDOR 198 | void print_winner(void) 199 | { 200 | for (int i = 0; i < candidate_count; i++) 201 | { 202 | bool isLoser = false; 203 | for (int j = 0; j < candidate_count; j++) 204 | { 205 | if (locked[j][i]) 206 | { 207 | isLoser = true; 208 | break; 209 | } 210 | 211 | } 212 | 213 | if (isLoser) continue; 214 | if(!isLoser) 215 | { 216 | printf("%s\n", candidates[i]); 217 | } 218 | } 219 | return; 220 | } 221 | -------------------------------------------------------------------------------- /03-CS50-CÓDIGO - RUNOFF: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // NUMERO MAXIMO DE CANDIDATOS E VOTOS 8 | #define MAX_CANDIDATES 9 9 | #define MAX_VOTERS 100 10 | 11 | // PREFERENCIAS DE VOTOS E CANDIDATOS 12 | int preferences[MAX_VOTERS][MAX_CANDIDATES]; 13 | 14 | // NOME E CONTAGEM DEM VOTOS 15 | typedef struct 16 | { 17 | string name; 18 | int votes; 19 | bool eliminated; 20 | } 21 | candidate; 22 | 23 | // ARRAY DE CANDIDATOS 24 | candidate candidates[MAX_CANDIDATES]; 25 | 26 | // NUMERO DE CANDIDATOS E VOTOS 27 | int voter_count; 28 | int candidate_count; 29 | 30 | // PROTOTIPOS DE FUNCAO 31 | bool vote(int voter, int rank, string name); 32 | void tabulate(void); 33 | bool print_winner(void); 34 | int find_min(void); 35 | bool is_tie(int min); 36 | void eliminate(int min); 37 | 38 | int main(int argc, string argv[]) 39 | { 40 | // VERIFIQUE INVALIDADE 41 | if (argc < 2) 42 | { 43 | printf("COLOQUE NOMES DOS CANDIDATOS DO SEGUNDO TURNO.\n"); 44 | return 1; 45 | } 46 | 47 | // MATRIZ DE CANDIDATOS 48 | candidate_count = argc - 1; 49 | if (candidate_count > MAX_CANDIDATES) 50 | { 51 | printf("NUMERO MAXIMO DE CANDIDATOS É %i\n", MAX_CANDIDATES); 52 | return 2; 53 | } 54 | for (int i = 0; i < candidate_count; i++) 55 | { 56 | candidates[i].name = argv[i + 1]; 57 | candidates[i].votes = 0; 58 | candidates[i].eliminated = false; 59 | } 60 | 61 | voter_count = get_int("NUMERO DE ELEITORES: "); 62 | if (voter_count > MAX_VOTERS) 63 | { 64 | printf("NUMERO MAXIMO DE ELEITORES É %i\n", MAX_VOTERS); 65 | return 3; 66 | } 67 | 68 | // LOOP ELEITORES 69 | for (int i = 0; i < voter_count; i++) 70 | { 71 | //CONSULTA CLASSIFICAÇÃO 72 | for (int j = 0; j < candidate_count; j++) 73 | { 74 | string name = get_string("CLASSIFICAÇÃO %i: ", j + 1); 75 | if (!vote(i, j, name)) 76 | { 77 | printf("VOTO INVALIDO.\n"); 78 | return 4; 79 | } 80 | } 81 | printf("\n"); 82 | 83 | } 84 | 85 | while (true) 86 | { 87 | //VOTOS CANDIDATOS RESTANTES 88 | tabulate(); 89 | 90 | bool won = print_winner(); 91 | if (won) 92 | { 93 | break; 94 | } 95 | 96 | //ELIMINAR CANDIDATOS EM ULTIMO LUGAR 97 | int min = find_min(); 98 | bool tie = is_tie(min); 99 | 100 | // EMPATE, TODOS GANHAM 101 | if (tie) 102 | 103 | { 104 | for (int i = 0; i < candidate_count; i++) 105 | { 106 | if (!candidates[i].eliminated) 107 | { 108 | printf("%s\n", candidates[i].name); 109 | } 110 | } 111 | break; 112 | } 113 | 114 | //ELIMINE NUMERO MINIMO DE VOTOS 115 | eliminate(min); 116 | 117 | for (int i = 0; i < candidate_count; i++) 118 | { 119 | candidates[i].votes = 0; 120 | } 121 | } 122 | return 0; 123 | } 124 | 125 | // PREFERENCIA DE REGISTRO DE VOTO VÁLIDO 126 | bool vote(int voter, int rank, string name) 127 | 128 | { 129 | bool exist = false; 130 | for (int i = 0; i < candidate_count; i++) 131 | { 132 | if (strcmp(name, candidates[i].name) == 0) 133 | { 134 | preferences[voter][rank] = i; 135 | exist = true; 136 | break; 137 | } 138 | } 139 | return exist; 140 | } 141 | 142 | // CANDIDATOS NÃO ELIMINADOS 143 | void tabulate(void) 144 | 145 | { 146 | for (int i = 0; i < voter_count; i++) 147 | { 148 | for (int j = 0; j < candidate_count; j++) 149 | { 150 | if (candidates[preferences[i][j]].eliminated == false) 151 | { 152 | candidates[preferences[i][j]].votes += 1; 153 | break; 154 | } 155 | } 156 | } 157 | return; 158 | } 159 | 160 | // IMPRIMIR VENCEDOR 161 | bool print_winner(void) 162 | { 163 | for (int i = 0; i < candidate_count; i++) 164 | { 165 | string most = candidates[i].name; 166 | if (candidates[i].votes > voter_count / 2) 167 | { 168 | printf("%s\n", most); 169 | return true; 170 | } 171 | } 172 | return false; 173 | } 174 | 175 | // DEVOLVE VOTOS RESTANTES 176 | int find_min(void) 177 | { 178 | int minvotes = voter_count; 179 | for (int i = 0; i < candidate_count; i++) 180 | { 181 | if (candidates[i].eliminated == false && candidates[i].votes < minvotes) 182 | { 183 | minvotes = candidates[i].votes; 184 | } 185 | } 186 | return minvotes; 187 | } 188 | bool is_tie(int minvotes) 189 | { 190 | for (int i = 0; i < candidate_count; i++) 191 | { 192 | if (candidates[i].eliminated == false && candidates[i].votes != minvotes) 193 | { 194 | return false; 195 | } 196 | } 197 | return true; 198 | } 199 | 200 | // ELIMINAR CANDIDATOS 201 | void eliminate(int minvotes) 202 | { 203 | for (int i = 0; i < candidate_count; i++) 204 | if (candidates[i].votes == minvotes) 205 | { 206 | candidates[i].eliminated = true; 207 | } 208 | return; 209 | } 210 | -------------------------------------------------------------------------------- /03-CS50-CÓDIGO - FILTRO 1: -------------------------------------------------------------------------------- 1 | #include 2 | #include "helpers.h" 3 | 4 | // Convert image to grayscale 5 | void grayscale(int height, int width, RGBTRIPLE image[height][width]) 6 | { 7 | for (int i = 0; i < height; i++) 8 | { 9 | for (int j = 0; j < width; j++) 10 | { 11 | RGBTRIPLE rgb = image[i][j]; 12 | int avg = (rgb.rgbtRed + rgb.rgbtGreen + rgb.rgbtBlue) / 3; 13 | 14 | RGBTRIPLE newrgb; 15 | newrgb.rgbtRed = avg; 16 | newrgb.rgbtGreen = avg; 17 | newrgb.rgbtBlue = avg; 18 | 19 | image[i][j] = newrgb; 20 | } 21 | } 22 | return; 23 | } 24 | 25 | // Convert image to sepia 26 | void sepia(int height, int width, RGBTRIPLE image[height][width]) 27 | { 28 | for (int i = 0; i < height; i++) 29 | { 30 | for (int j = 0; j < width; j++) 31 | { 32 | RGBTRIPLE rgb = image[i][j]; 33 | BYTE originalRed = rgb.rgbtRed; 34 | BYTE originalGreen = rgb.rgbtGreen; 35 | BYTE originalBlue = rgb.rgbtBlue; 36 | 37 | float sepiaRed = .393 * originalRed + .769 * originalGreen + .189 * originalBlue; 38 | float sepiaGreen = .349 * originalRed + .686 * originalGreen + .168 * originalBlue; 39 | float sepiaBlue = .272 * originalRed + .534 * originalGreen + .131 * originalBlue; 40 | 41 | RGBTRIPLE newrgb; 42 | newrgb.rgbtRed = sepiaRed > 255 ? 255 : sepiaRed; 43 | newrgb.rgbtGreen = sepiaGreen > 255 ? 255 : sepiaGreen; 44 | newrgb.rgbtBlue = sepiaBlue > 255 ? 255 : sepiaBlue; 45 | 46 | image[i][j] = newrgb; 47 | } 48 | } 49 | return; 50 | } 51 | 52 | // Reflect image horizontally 53 | void reflect(int height, int width, RGBTRIPLE image[height][width]) 54 | { 55 | for (int i = 0; i < height; i++) 56 | { 57 | for (int j = 0; j < width / 2; j++) 58 | { 59 | RGBTRIPLE temp = image[i][j]; 60 | image[i][j] = image[i][width - j]; 61 | image[i][width - j] = temp; 62 | } 63 | } 64 | return; 65 | } 66 | 67 | // Blur image 68 | void blur(int height, int width, RGBTRIPLE image[height][width]) 69 | { 70 | RGBTRIPLE aux[height + 2][width + 2]; 71 | 72 | for (int i = 0; i < height + 2; i++) 73 | { 74 | for (int j = 0; j < width + 2; j++) 75 | { 76 | if (i == 0 || i == height + 1 || j == 0 || j == width + 1) 77 | { 78 | RGBTRIPLE newrgb; 79 | newrgb.rgbtRed = 0; 80 | newrgb.rgbtGreen = 0; 81 | newrgb.rgbtBlue = 0; 82 | 83 | aux[i][j] = newrgb; 84 | } 85 | else 86 | aux[i][j] = image[i - 1][j - 1]; 87 | } 88 | } 89 | 90 | for (int i = 1; i < height + 1; i++) 91 | { 92 | for (int j = 1; j < width + 1; j++) 93 | { 94 | RGBTRIPLE newrgb; 95 | RGBTRIPLE tl = aux[i - 1][j - 1]; 96 | RGBTRIPLE tc = aux[i - 1][j + 0]; 97 | RGBTRIPLE tr = aux[i - 1][j + 1]; 98 | RGBTRIPLE ml = aux[i + 0][j - 1]; 99 | RGBTRIPLE mr = aux[i + 0][j + 1]; 100 | RGBTRIPLE bl = aux[i + 1][j - 1]; 101 | RGBTRIPLE bc = aux[i + 1][j + 0]; 102 | RGBTRIPLE br = aux[i + 1][j + 1]; 103 | 104 | int div = 8; 105 | 106 | if (i == 1 || i == height || j == 1 || j == width) 107 | div = 5; 108 | if ((i == 1 && (j == 1 || j == width)) || (i == height && (j == 1 || j == width))) 109 | div = 3; 110 | 111 | BYTE blurRed = (tl.rgbtRed + tc.rgbtRed + tr.rgbtRed + ml.rgbtRed + mr.rgbtRed + bl.rgbtRed + bc.rgbtRed + br.rgbtRed) / div; 112 | BYTE blurGreen = (tl.rgbtGreen + tc.rgbtGreen + tr.rgbtGreen + ml.rgbtGreen + mr.rgbtGreen + bl.rgbtGreen + bc.rgbtGreen + br.rgbtGreen) / div; 113 | BYTE blurBlue = (tl.rgbtBlue + tc.rgbtBlue + tr.rgbtBlue + ml.rgbtBlue + mr.rgbtBlue + bl.rgbtBlue + bc.rgbtBlue + br.rgbtBlue) / div; 114 | 115 | newrgb.rgbtRed = blurRed; 116 | newrgb.rgbtGreen = blurGreen; 117 | newrgb.rgbtBlue = blurBlue; 118 | 119 | image[i][j] = newrgb; 120 | } 121 | } 122 | return; 123 | } 124 | 125 | // Edges 126 | void edges(int height, int width, RGBTRIPLE image[height][width]) 127 | { 128 | RGBTRIPLE aux[height + 2][width + 2]; 129 | 130 | for (int i = 0; i < height + 2; i++) 131 | { 132 | for (int j = 0; j < width + 2; j++) 133 | { 134 | if (i == 0 || i == height + 1 || j == 0 || j == width + 1) 135 | { 136 | RGBTRIPLE newrgb; 137 | newrgb.rgbtRed = 0; 138 | newrgb.rgbtGreen = 0; 139 | newrgb.rgbtBlue = 0; 140 | 141 | aux[i][j] = newrgb; 142 | } 143 | else 144 | aux[i][j] = image[i - 1][j - 1]; 145 | } 146 | } 147 | 148 | for (int i = 1; i < height + 1; i++) 149 | { 150 | for (int j = 1; j < width + 1; j++) 151 | { 152 | RGBTRIPLE newrgb; 153 | RGBTRIPLE tl = aux[i - 1][j - 1]; 154 | RGBTRIPLE tc = aux[i - 1][j + 0]; 155 | RGBTRIPLE tr = aux[i - 1][j + 1]; 156 | RGBTRIPLE ml = aux[i + 0][j - 1]; 157 | RGBTRIPLE mr = aux[i + 0][j + 1]; 158 | RGBTRIPLE bl = aux[i + 1][j - 1]; 159 | RGBTRIPLE bc = aux[i + 1][j + 0]; 160 | RGBTRIPLE br = aux[i + 1][j + 1]; 161 | 162 | float GxRed = (tl.rgbtRed * -1 + tc.rgbtRed * 0 + tr.rgbtRed * 1 + 163 | ml.rgbtRed * -2 + mr.rgbtRed * 2 + 164 | bl.rgbtRed * -1 + bc.rgbtRed * 0 + br.rgbtRed * 1); 165 | float GxGreen = (tl.rgbtGreen * -1 + tc.rgbtGreen * 0 + tr.rgbtGreen * 1 + 166 | ml.rgbtGreen * -2 + mr.rgbtGreen * 2 + 167 | bl.rgbtGreen * -1 + bc.rgbtGreen * 0 + br.rgbtGreen * 1); 168 | float GxBlue = (tl.rgbtBlue * -1 + tc.rgbtBlue * 0 + tr.rgbtBlue * 1 + 169 | ml.rgbtBlue * -2 + mr.rgbtBlue * 2 + 170 | bl.rgbtBlue * -1 + bc.rgbtBlue * 0 + br.rgbtBlue * 1); 171 | 172 | float GyRed = (tl.rgbtRed * -1 + tc.rgbtRed * -2 + tr.rgbtRed * -1 + 173 | ml.rgbtRed * -0 + mr.rgbtRed * 0 + 174 | bl.rgbtRed * 1 + bc.rgbtRed * 2 + br.rgbtRed * 1); 175 | float GyGreen = (tl.rgbtGreen * -1 + tc.rgbtGreen * -2 + tr.rgbtGreen * -1 + 176 | ml.rgbtGreen * -0 + mr.rgbtGreen * 0 + 177 | bl.rgbtGreen * 1 + bc.rgbtGreen * 2 + br.rgbtGreen * 1); 178 | float GyBlue = (tl.rgbtBlue * -1 + tc.rgbtBlue * -2 + tr.rgbtBlue * -1 + 179 | ml.rgbtBlue * 0 + mr.rgbtBlue * 0 + 180 | bl.rgbtBlue * 1 + bc.rgbtBlue * 2 + br.rgbtBlue * 1); 181 | 182 | float red = sqrtf(powf(GxRed, 2) + powf(GyRed, 2)); 183 | float green = sqrtf(powf(GxGreen, 2) + powf(GyGreen, 2)); 184 | float blue = sqrtf(powf(GxBlue, 2) + powf(GyBlue, 2)); 185 | 186 | newrgb.rgbtRed = red > 255 ? 255 : red; 187 | newrgb.rgbtGreen = green > 255 ? 255 : green; 188 | newrgb.rgbtBlue = blue > 255 ? 255 : blue; 189 | 190 | image[i][j] = newrgb; 191 | } 192 | } 193 | return; 194 | } 195 | -------------------------------------------------------------------------------- /04-CS50-CÓDIGO - FILTRO 1: -------------------------------------------------------------------------------- 1 | #include 2 | #include "helpers.h" 3 | 4 | // Convert image to grayscale 5 | void grayscale(int height, int width, RGBTRIPLE image[height][width]) 6 | { 7 | for (int i = 0; i < height; i++) 8 | { 9 | for (int j = 0; j < width; j++) 10 | { 11 | RGBTRIPLE rgb = image[i][j]; 12 | int avg = (rgb.rgbtRed + rgb.rgbtGreen + rgb.rgbtBlue) / 3; 13 | 14 | RGBTRIPLE newrgb; 15 | newrgb.rgbtRed = avg; 16 | newrgb.rgbtGreen = avg; 17 | newrgb.rgbtBlue = avg; 18 | 19 | image[i][j] = newrgb; 20 | } 21 | } 22 | return; 23 | } 24 | 25 | // Convert image to sepia 26 | void sepia(int height, int width, RGBTRIPLE image[height][width]) 27 | { 28 | for (int i = 0; i < height; i++) 29 | { 30 | for (int j = 0; j < width; j++) 31 | { 32 | RGBTRIPLE rgb = image[i][j]; 33 | BYTE originalRed = rgb.rgbtRed; 34 | BYTE originalGreen = rgb.rgbtGreen; 35 | BYTE originalBlue = rgb.rgbtBlue; 36 | 37 | float sepiaRed = .393 * originalRed + .769 * originalGreen + .189 * originalBlue; 38 | float sepiaGreen = .349 * originalRed + .686 * originalGreen + .168 * originalBlue; 39 | float sepiaBlue = .272 * originalRed + .534 * originalGreen + .131 * originalBlue; 40 | 41 | RGBTRIPLE newrgb; 42 | newrgb.rgbtRed = sepiaRed > 255 ? 255 : sepiaRed; 43 | newrgb.rgbtGreen = sepiaGreen > 255 ? 255 : sepiaGreen; 44 | newrgb.rgbtBlue = sepiaBlue > 255 ? 255 : sepiaBlue; 45 | 46 | image[i][j] = newrgb; 47 | } 48 | } 49 | return; 50 | } 51 | 52 | // Reflect image horizontally 53 | void reflect(int height, int width, RGBTRIPLE image[height][width]) 54 | { 55 | for (int i = 0; i < height; i++) 56 | { 57 | for (int j = 0; j < width / 2; j++) 58 | { 59 | RGBTRIPLE temp = image[i][j]; 60 | image[i][j] = image[i][width - j]; 61 | image[i][width - j] = temp; 62 | } 63 | } 64 | return; 65 | } 66 | 67 | // Blur image 68 | void blur(int height, int width, RGBTRIPLE image[height][width]) 69 | { 70 | RGBTRIPLE aux[height + 2][width + 2]; 71 | 72 | for (int i = 0; i < height + 2; i++) 73 | { 74 | for (int j = 0; j < width + 2; j++) 75 | { 76 | if (i == 0 || i == height + 1 || j == 0 || j == width + 1) 77 | { 78 | RGBTRIPLE newrgb; 79 | newrgb.rgbtRed = 0; 80 | newrgb.rgbtGreen = 0; 81 | newrgb.rgbtBlue = 0; 82 | 83 | aux[i][j] = newrgb; 84 | } 85 | else 86 | aux[i][j] = image[i - 1][j - 1]; 87 | } 88 | } 89 | 90 | for (int i = 1; i < height + 1; i++) 91 | { 92 | for (int j = 1; j < width + 1; j++) 93 | { 94 | RGBTRIPLE newrgb; 95 | RGBTRIPLE tl = aux[i - 1][j - 1]; 96 | RGBTRIPLE tc = aux[i - 1][j + 0]; 97 | RGBTRIPLE tr = aux[i - 1][j + 1]; 98 | RGBTRIPLE ml = aux[i + 0][j - 1]; 99 | RGBTRIPLE mr = aux[i + 0][j + 1]; 100 | RGBTRIPLE bl = aux[i + 1][j - 1]; 101 | RGBTRIPLE bc = aux[i + 1][j + 0]; 102 | RGBTRIPLE br = aux[i + 1][j + 1]; 103 | 104 | int div = 8; 105 | 106 | if (i == 1 || i == height || j == 1 || j == width) 107 | div = 5; 108 | if ((i == 1 && (j == 1 || j == width)) || (i == height && (j == 1 || j == width))) 109 | div = 3; 110 | 111 | BYTE blurRed = (tl.rgbtRed + tc.rgbtRed + tr.rgbtRed + ml.rgbtRed + mr.rgbtRed + bl.rgbtRed + bc.rgbtRed + br.rgbtRed) / div; 112 | BYTE blurGreen = (tl.rgbtGreen + tc.rgbtGreen + tr.rgbtGreen + ml.rgbtGreen + mr.rgbtGreen + bl.rgbtGreen + bc.rgbtGreen + br.rgbtGreen) / div; 113 | BYTE blurBlue = (tl.rgbtBlue + tc.rgbtBlue + tr.rgbtBlue + ml.rgbtBlue + mr.rgbtBlue + bl.rgbtBlue + bc.rgbtBlue + br.rgbtBlue) / div; 114 | 115 | newrgb.rgbtRed = blurRed; 116 | newrgb.rgbtGreen = blurGreen; 117 | newrgb.rgbtBlue = blurBlue; 118 | 119 | image[i][j] = newrgb; 120 | } 121 | } 122 | return; 123 | } 124 | 125 | // Edges 126 | void edges(int height, int width, RGBTRIPLE image[height][width]) 127 | { 128 | RGBTRIPLE aux[height + 2][width + 2]; 129 | 130 | for (int i = 0; i < height + 2; i++) 131 | { 132 | for (int j = 0; j < width + 2; j++) 133 | { 134 | if (i == 0 || i == height + 1 || j == 0 || j == width + 1) 135 | { 136 | RGBTRIPLE newrgb; 137 | newrgb.rgbtRed = 0; 138 | newrgb.rgbtGreen = 0; 139 | newrgb.rgbtBlue = 0; 140 | 141 | aux[i][j] = newrgb; 142 | } 143 | else 144 | aux[i][j] = image[i - 1][j - 1]; 145 | } 146 | } 147 | 148 | for (int i = 1; i < height + 1; i++) 149 | { 150 | for (int j = 1; j < width + 1; j++) 151 | { 152 | RGBTRIPLE newrgb; 153 | RGBTRIPLE tl = aux[i - 1][j - 1]; 154 | RGBTRIPLE tc = aux[i - 1][j + 0]; 155 | RGBTRIPLE tr = aux[i - 1][j + 1]; 156 | RGBTRIPLE ml = aux[i + 0][j - 1]; 157 | RGBTRIPLE mr = aux[i + 0][j + 1]; 158 | RGBTRIPLE bl = aux[i + 1][j - 1]; 159 | RGBTRIPLE bc = aux[i + 1][j + 0]; 160 | RGBTRIPLE br = aux[i + 1][j + 1]; 161 | 162 | float GxRed = (tl.rgbtRed * -1 + tc.rgbtRed * 0 + tr.rgbtRed * 1 + 163 | ml.rgbtRed * -2 + mr.rgbtRed * 2 + 164 | bl.rgbtRed * -1 + bc.rgbtRed * 0 + br.rgbtRed * 1); 165 | float GxGreen = (tl.rgbtGreen * -1 + tc.rgbtGreen * 0 + tr.rgbtGreen * 1 + 166 | ml.rgbtGreen * -2 + mr.rgbtGreen * 2 + 167 | bl.rgbtGreen * -1 + bc.rgbtGreen * 0 + br.rgbtGreen * 1); 168 | float GxBlue = (tl.rgbtBlue * -1 + tc.rgbtBlue * 0 + tr.rgbtBlue * 1 + 169 | ml.rgbtBlue * -2 + mr.rgbtBlue * 2 + 170 | bl.rgbtBlue * -1 + bc.rgbtBlue * 0 + br.rgbtBlue * 1); 171 | 172 | float GyRed = (tl.rgbtRed * -1 + tc.rgbtRed * -2 + tr.rgbtRed * -1 + 173 | ml.rgbtRed * -0 + mr.rgbtRed * 0 + 174 | bl.rgbtRed * 1 + bc.rgbtRed * 2 + br.rgbtRed * 1); 175 | float GyGreen = (tl.rgbtGreen * -1 + tc.rgbtGreen * -2 + tr.rgbtGreen * -1 + 176 | ml.rgbtGreen * -0 + mr.rgbtGreen * 0 + 177 | bl.rgbtGreen * 1 + bc.rgbtGreen * 2 + br.rgbtGreen * 1); 178 | float GyBlue = (tl.rgbtBlue * -1 + tc.rgbtBlue * -2 + tr.rgbtBlue * -1 + 179 | ml.rgbtBlue * 0 + mr.rgbtBlue * 0 + 180 | bl.rgbtBlue * 1 + bc.rgbtBlue * 2 + br.rgbtBlue * 1); 181 | 182 | float red = sqrtf(powf(GxRed, 2) + powf(GyRed, 2)); 183 | float green = sqrtf(powf(GxGreen, 2) + powf(GyGreen, 2)); 184 | float blue = sqrtf(powf(GxBlue, 2) + powf(GyBlue, 2)); 185 | 186 | newrgb.rgbtRed = red > 255 ? 255 : red; 187 | newrgb.rgbtGreen = green > 255 ? 255 : green; 188 | newrgb.rgbtBlue = blue > 255 ? 255 : blue; 189 | 190 | image[i][j] = newrgb; 191 | } 192 | } 193 | return; 194 | } 195 | -------------------------------------------------------------------------------- /09-CS50-CÓDIGO - FLASK - application.py - FINANCE -: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from cs50 import SQL 4 | from flask import Flask, flash, redirect, render_template, request, session 5 | from flask_session import Session 6 | from tempfile import mkdtemp 7 | from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError 8 | from werkzeug.security import check_password_hash, generate_password_hash 9 | from helpers import apology, login_required, lookup, usd 10 | from datetime import datetime 11 | 12 | # CONFIGURAÇÃO APLICAÇÃO 13 | app = Flask(__name__) 14 | 15 | # RECARREGAR AUTOMATICAMENTE 16 | app.config["TEMPLATES_AUTO_RELOAD"] = True 17 | 18 | # NÃO ARMAZENAR CACHE 19 | @app.after_request 20 | def after_request(response): 21 | response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" 22 | response.headers["Expires"] = 0 23 | response.headers["Pragma"] = "no-cache" 24 | return response 25 | 26 | # FILTRO 27 | app.jinja_env.filters["usd"] = usd 28 | 29 | # SISTEMA DE ARQUIVOS 30 | app.config["SESSION_FILE_DIR"] = mkdtemp() 31 | app.config["SESSION_PERMANENT"] = False 32 | app.config["SESSION_TYPE"] = "filesystem" 33 | Session(app) 34 | 35 | # BIBLIOTECA CS50 - SQLite 36 | db = SQL("sqlite:///finance.db") 37 | 38 | # DEFINIR CHAVE API 39 | if not os.environ.get("API_KEY"): 40 | raise RuntimeError("API_KEY not set") 41 | 42 | @app.route("/") 43 | @login_required 44 | def index(): 45 | #PREÇO 46 | stocks={} 47 | #LISTA DE AÇÕES 48 | stock_list = db.execute("SELECT symbol FROM (SELECT * FROM transactions GROUP BY symbol) WHERE user_id=?", session["user_id"]) 49 | #VALORES 50 | cash = db.execute("SELECT cash FROM users where id=?", session["user_id"])[0]["cash"] 51 | #TOTAL AGREGADO 52 | total = 0 53 | 54 | #PESQUISA PREÇO ATUAL 55 | 56 | for stock in stock_list: 57 | if db.execute("SELECT SUM(shares) FROM transactions WHERE symbol=?", stock["symbol"])[0]["SUM(shares)"]>0: 58 | info = lookup(stock["symbol"]) 59 | info["shares"] = db.execute("SELECT SUM(shares) FROM transactions WHERE symbol=?", info["symbol"])[0]["SUM(shares)"] 60 | info["total"] = info["shares"] * info["price"] 61 | total += info["total"] 62 | stocks[stock["symbol"]] = info 63 | 64 | total += cash 65 | 66 | return render_template("index.html", stocks=stocks, cash=cash, total=total) 67 | 68 | @app.route("/buy", methods=["GET", "POST"]) 69 | @login_required 70 | def buy(): 71 | if request.method == "POST": 72 | 73 | #VARIAVEIS LOGICAS PARA TESTE 74 | stock = lookup(request.form.get("symbol")) 75 | if not stock: 76 | return apology("must provide valid symbol", 400) 77 | cash = db.execute("SELECT cash FROM users WHERE id=?", session["user_id"])[0]["cash"] 78 | try: 79 | shares = int(request.form.get("shares")) 80 | except: 81 | return apology("must provide integer amount", 400) 82 | 83 | #ERROS 84 | if shares < 1: 85 | return apology("must provide valid quantity", 400) 86 | if (shares*stock["price"]) > cash: 87 | return apology("Not enough money for the buy", 400) 88 | 89 | #NÃO CONTER ERROS - USUÁRIO COMPRARÁ AÇÕES - INFORMAÇÕES SOBRE AÇÕES BANCO DE DADOS 90 | db.execute("INSERT INTO transactions (user_id, symbol, price, shares, time, type) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], stock["symbol"], stock["price"], shares, datetime.now(), "Bought") 91 | 92 | #VALOR ATUAL 93 | db.execute("UPDATE users SET cash=? WHERE id=?", cash-(shares*stock["price"]), session["user_id"]) 94 | 95 | #REDIRECIONA INDICE 96 | return redirect("/") 97 | 98 | return render_template("buy.html") 99 | 100 | @app.route("/history") 101 | @login_required 102 | def history(): 103 | #LISTA TODAS AÇÕES 104 | stocks={} 105 | transactions = db.execute("SELECT * FROM transactions WHERE user_id=? ORDER BY time", session["user_id"]) 106 | 107 | return render_template("history.html", transactions=transactions) 108 | 109 | @app.route("/login", methods=["GET", "POST"]) 110 | def login(): 111 | """Log user in""" 112 | 113 | #ESQUECER USUÁRIO 114 | session.clear() 115 | 116 | #CORREIOS 117 | if request.method == "POST": 118 | 119 | #NOME USUÁRIO ENVIADO 120 | if not request.form.get("username"): 121 | return apology("must provide username", 400) 122 | 123 | #SENHA ENVIADA 124 | elif not request.form.get("password"): 125 | return apology("must provide password", 400) 126 | 127 | #BANCO DE DADOS CONSULTA USUÁRIO 128 | rows = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username")) 129 | 130 | 131 | #USUÁRIO E SENHA - EXISTENTE E CORRETOS 132 | if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")): 133 | return apology("invalid username and/or password", 400) 134 | 135 | #LEMBRAR LOGIN 136 | session["user_id"] = rows[0]["id"] 137 | 138 | #PAGINA INICIAL 139 | return redirect("/") 140 | 141 | #USUÁRIO ALCANÇOU ROTA VIA GET 142 | else: 143 | return render_template("login.html") 144 | 145 | @app.route("/logout") 146 | def logout(): 147 | """Log user out""" 148 | 149 | #ESQUECER USUÁRIO 150 | session.clear() 151 | 152 | #REDIRECIONAR LOGIN 153 | return redirect("/") 154 | 155 | @app.route("/quote", methods=["GET", "POST"]) 156 | @login_required 157 | def quote(): 158 | if request.method == "POST": 159 | stock = lookup(request.form.get("symbol")) 160 | if not stock: 161 | return apology("must provide valid symbol", 400) 162 | return render_template("quoted.html", stock=stock) 163 | return render_template("quote.html") 164 | 165 | @app.route("/register", methods=["GET", "POST"]) 166 | def register(): 167 | 168 | if request.method == "POST": 169 | 170 | username = request.form.get("username") 171 | password = request.form.get("password") 172 | number=[0,1,2,3,4,5,6,7,8,9] 173 | valid_symbols = "!@#$%^&*()_-+={}[]" 174 | count_number = 0 175 | 176 | #ERROS DE SENHA 177 | hashed = generate_password_hash(password) 178 | rows = db.execute("SELECT username FROM users WHERE username=?", username) 179 | 180 | #MANIPULAR ERROS 181 | if not username: 182 | return apology("must provide username", 400) 183 | 184 | if password != request.form.get("confirmation") or not password: 185 | return apology("must provide valid password", 400) 186 | 187 | if len(rows) > 0: 188 | return apology("Username already used", 400) 189 | 190 | #ADICIONAR INFORMAÇÃO 191 | db.execute("INSERT INTO users (username, hash) VALUES (?,?)", username, hashed) 192 | 193 | return redirect("/") 194 | 195 | """Register user""" 196 | return render_template("register.html") 197 | 198 | @app.route("/sell", methods=["GET", "POST"]) 199 | @login_required 200 | def sell(): 201 | 202 | symbols = db.execute("SELECT symbol FROM transactions GROUP BY symbol HAVING user_id=?", session["user_id"]) 203 | stock_list = [] 204 | 205 | for item in symbols: 206 | stock_list.append(item["symbol"]) 207 | 208 | #CHECAR PARTICIPAÇÕES 209 | for item in stock_list: 210 | if db.execute("SELECT SUM(shares) FROM transactions WHERE symbol=? GROUP BY symbol HAVING user_id=?", item, session["user_id"])[0]["SUM(shares)"] < 1: 211 | print(stock_list) 212 | print(item) 213 | stock_list.remove(item) 214 | print(stock_list) 215 | 216 | if request.method == "POST": 217 | try: 218 | shares = int(request.form.get("shares")) 219 | except: 220 | return apology("must provide integer amount", 400) 221 | 222 | stock = lookup(request.form.get("symbol")) 223 | 224 | if not stock: 225 | return apology("must provide valid symbol", 400) 226 | 227 | for item in symbols: 228 | stock_list.append(item["symbol"]) 229 | 230 | if stock["symbol"] not in stock_list: 231 | return apology("must provide valid symbol", 400) 232 | 233 | #VARIÁVEIS TESTE 234 | cash = db.execute("SELECT cash FROM users WHERE id=?", session["user_id"])[0]["cash"] 235 | hold = db.execute("SELECT SUM(shares) FROM transactions WHERE symbol=? GROUP BY symbol HAVING user_id=?", stock["symbol"], session["user_id"])[0]["SUM(shares)"] 236 | 237 | #CHECAR AÇÕES INTERIAS - ERRO DE MANUSEIO 238 | if shares < 1: 239 | return apology("must provide valid quantity", 400) 240 | if hold < shares: 241 | return apology("Not enough stocks for the sell", 400) 242 | 243 | #PASSAR TESTE - USUÁRIO COMPRA AÇÕES - INFORMAÇÕES AÇÕES BANCO DE DADOS 244 | db.execute("INSERT INTO transactions (user_id, symbol, price, shares, time, type) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], stock["symbol"], stock["price"], -shares, datetime.now(), "Sold") 245 | 246 | #VALOR ATUAL 247 | db.execute("UPDATE users SET cash=? WHERE id=?", cash+(shares*stock["price"]), session["user_id"]) 248 | 249 | #REDIRECIONA PAGINA INICIAL 250 | return redirect("/") 251 | 252 | return render_template("sell.html", symbols=stock_list) 253 | 254 | def errorhandler(e): 255 | """Handle error""" 256 | if not isinstance(e, HTTPException): 257 | e = InternalServerError() 258 | return apology(e.name, e.code) 259 | 260 | #LISTA DE ERROS 261 | for code in default_exceptions: 262 | app.errorhandler(code)(errorhandler) 263 | --------------------------------------------------------------------------------