├── usando-o-pydantic ├── books │ ├── __init__.py │ ├── validators.py │ └── models.py ├── requirements.txt ├── exemplo_com_um_livro.py ├── exemplo_com_muitos_livros.py └── livros.json ├── mais-decoradores-em-python ├── module │ ├── __init__.py │ ├── colors.py │ └── decorators.py ├── colorido.py ├── simples.py ├── argumentos.py └── multiplica.py ├── convertendo-imagens-para-msx ├── requirements.txt ├── dithered.png ├── reduced.bas ├── reduced.png ├── dithered.bas ├── interlaced.png ├── sample_256x192.png ├── sample_256x384.png ├── sample_512x384.png ├── sunset_256x384.png ├── interlac.bas ├── .editorconfig ├── reducing.py ├── dithering.py ├── interlacing.py └── functions.py ├── criando-imagens-em-python ├── requirements.txt ├── outro_teste_pillow.py ├── teste_pillow.py └── mandelbrot.py ├── .gitignore ├── convertendo-imagens-para-16-cores-do-msx ├── .gitignore ├── sample_256x192.png ├── sample_512x384.png ├── LOADER5.BAS ├── LOADER7.BAS ├── quantization.py ├── reducing.py ├── couting.py ├── converting.py └── functions.py ├── modulos-em-python ├── media.py ├── meus_modulos │ ├── __init__.py │ └── calculos.py ├── 2_funcao_fora_do_programa.py ├── 1_funcao_dentro_do_programa.py ├── 4_classe_fora_do_programa.py ├── 6_modulo_em_outro_diretorio_2.py ├── 5_modulo_em_outro_diretorio.py ├── calculos.py ├── 7_modulo_carregado_em_tmp.py └── 3_classe_dentro_do_programa.py ├── manipulando-xlsx-em-python ├── requirements.txt ├── aleatórios.xlsx ├── create_worksheet.py ├── retrieve_worksheet.py ├── convert_csv_to_xlsx.py ├── students.csv └── server.py ├── cobertura-de-codigo-com-pytest ├── requirements.txt ├── htmlcov │ ├── keybd_open.png │ ├── keybd_closed.png │ ├── status.json │ ├── jquery.ba-throttle-debounce.min.js │ ├── jquery.isonscreen.js │ ├── index.html │ ├── jquery.hotkeys.js │ ├── style.css │ └── pode_beber_py.html └── pode_beber.py ├── incrementando-o-tetris-do-msx1 ├── tetris_disk.zip └── tetris_files.zip ├── convertendo-imagens-para-o-atari-st ├── cosmotro.pi1 ├── mountain.pi3 ├── requirements.txt ├── reading.py └── degas.py ├── geradores-em-python ├── um_elemento_por_vez.py ├── cria_diretorios.sh ├── diretorio.py └── alfabeto.py ├── um-basico-de-pytest ├── programa.py ├── alunos.json ├── alunos.py └── medias.py ├── registro-de-eventos-em-python ├── programa_de_teste.py ├── registro_em_arquivo.log ├── registro_em_disco.py ├── segundo_exemplo.py └── hal_quotes.py ├── orientacao-a-objetos-em-ruby-o-basico ├── Supernome.rb ├── Nome.rb └── nome.rb ├── excecoes-em-python-parte-2 ├── tratando_o_raise.py ├── salva_arquivo-a.py ├── salva_arquivo-b.py ├── cavaleiro_negro.py └── CavaleiroNegro.py ├── argumentos-de-funcoes-em-python ├── concat.py └── argumentos.py ├── excecoes-em-python-parte-1 ├── contar_ate_100-a.py ├── contar_ate_100-b.py ├── contar_ate_100-c.py ├── contar_ate_100-b_while.py ├── contar_ate_100-d.py ├── contar_ate_100-e.py └── contar_ate_100-f.py ├── um-outro-exemplo-de-angularjs ├── exemplo-abj-2.json ├── exemplo-abj-2.css ├── exemplo-abj-2.js └── exemplo-abj-2.html ├── xml-em-perl-parte-3 ├── ped.ptxt ├── ped.phtml └── ped.pl ├── excecoes-em-python-parte-3 ├── minha_excecao.py ├── 2_hierarquia_incorreta.txt ├── 1_nivel_hierarquico_invalido.txt ├── municipios.py └── municipios_tb.py ├── orientacao-a-objetos-em-python-o-basico ├── nome.py └── nomes.py ├── usando-arquivos-csv-em-python ├── read_csv_file_as_dict.py ├── read_csv_file.py ├── write_csv_file.py ├── csv_as_variable.py ├── join_student_and_grades.py ├── students.csv └── write_csv_as_dict.py ├── decoradores-em-python ├── notas.json ├── funcao_como_objeto.py ├── funcao_como_argumento.py ├── funcao_decorada.py ├── funcao_decorada_como_argumento.py ├── testa_decoradores.py └── decoradores.py ├── orientacao-a-objetos-em-python-alem-do-basico ├── veiculos.py ├── computadores.py └── pessoas.py ├── exemplo-com-angularjs-bootstrap-e-jquery ├── exemplo-abj.css ├── exemplo-abj.html └── exemplo-abj.js ├── usando-grupos-em-expressoes-regulares ├── lorem_ipsum.py ├── lorem_ipsum.txt └── lorem_ipsum.html ├── orientacao-a-objetos-em-php-o-basico ├── nome.php ├── SuperNome.php ├── supernome.php └── Nome.php ├── um-basico-de-orientacao-a-objetos-em-perl ├── nome.pl └── Nome.pm ├── orientacao-a-objetos-em-javascript-o-basico ├── nome_ecma-262.js └── nome.js ├── quantos-dias-tem-um-mes └── numberofdays.sh ├── faxina-no-boot └── oldkernelcleaner.sh ├── maquina-virtual-em-perl └── mymac.pl ├── gerador-de-arquivos-ips ├── IPSmaker.pm └── ipsmaker.pl └── README.md /usando-o-pydantic/books/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/module/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow 2 | -------------------------------------------------------------------------------- /usando-o-pydantic/requirements.txt: -------------------------------------------------------------------------------- 1 | pydantic==1.10.13 2 | -------------------------------------------------------------------------------- /criando-imagens-em-python/requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow>7.0.0 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | */.pytest_cache 3 | /__pycache__/* 4 | py3/ 5 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/.gitignore: -------------------------------------------------------------------------------- 1 | *.P[57][01L] 2 | -------------------------------------------------------------------------------- /modulos-em-python/media.py: -------------------------------------------------------------------------------- 1 | def media(a, b): 2 | return (a + b)/2.0 3 | -------------------------------------------------------------------------------- /modulos-em-python/meus_modulos/__init__.py: -------------------------------------------------------------------------------- 1 | from calculos import Calculos 2 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/requirements.txt: -------------------------------------------------------------------------------- 1 | colorama==0.4.4 2 | Flask==2.3.2 3 | openpyxl==3.0.6 4 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/requirements.txt: -------------------------------------------------------------------------------- 1 | coverage==4.5.2 2 | pytest==4.0.1 3 | pytest-cov==2.6.0 4 | -------------------------------------------------------------------------------- /modulos-em-python/2_funcao_fora_do_programa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 2 3 | from media import media 4 | print(media(3, 2)) 5 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/dithered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/dithered.png -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/reduced.bas: -------------------------------------------------------------------------------- 1 | 10 COLOR 15,0,0 2 | 20 SCREEN 8:VDP(10)=VDP(10) AND &H7F 3 | 30 BLOAD "REDUCED.SC8",S 4 | 40 K$=INPUT$(1) -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/reduced.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/reduced.png -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/dithered.bas: -------------------------------------------------------------------------------- 1 | 10 COLOR 15,0,0 2 | 20 SCREEN 8:VDP(10)=VDP(10) AND &H7F 3 | 30 BLOAD "DITHERED.SC8",S 4 | 40 K$=INPUT$(1) -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/interlaced.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/interlaced.png -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/aleatórios.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/manipulando-xlsx-em-python/aleatórios.xlsx -------------------------------------------------------------------------------- /incrementando-o-tetris-do-msx1/tetris_disk.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/incrementando-o-tetris-do-msx1/tetris_disk.zip -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/sample_256x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/sample_256x192.png -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/sample_256x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/sample_256x384.png -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/sample_512x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/sample_512x384.png -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/sunset_256x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-msx/sunset_256x384.png -------------------------------------------------------------------------------- /convertendo-imagens-para-o-atari-st/cosmotro.pi1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-o-atari-st/cosmotro.pi1 -------------------------------------------------------------------------------- /convertendo-imagens-para-o-atari-st/mountain.pi3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-o-atari-st/mountain.pi3 -------------------------------------------------------------------------------- /incrementando-o-tetris-do-msx1/tetris_files.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/incrementando-o-tetris-do-msx1/tetris_files.zip -------------------------------------------------------------------------------- /modulos-em-python/1_funcao_dentro_do_programa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 1 3 | def media(a, b): 4 | return (a + b)/2.0 5 | 6 | print(media(3, 2)) 7 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/keybd_open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/cobertura-de-codigo-com-pytest/htmlcov/keybd_open.png -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/keybd_closed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/cobertura-de-codigo-com-pytest/htmlcov/keybd_closed.png -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/sample_256x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-16-cores-do-msx/sample_256x192.png -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/sample_512x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/plainspooky/giovannireisnunes/HEAD/convertendo-imagens-para-16-cores-do-msx/sample_512x384.png -------------------------------------------------------------------------------- /convertendo-imagens-para-o-atari-st/requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow==10.3.0 2 | divisivlelist @ git+https://github.com/plainspooky/divisiblelist@d9d309e1e6f018f18b5ab82fcc0b7c21cc0e8fd7 3 | -------------------------------------------------------------------------------- /modulos-em-python/4_classe_fora_do_programa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 4 3 | from calculos import Calculos 4 | 5 | calculos = Calculos(3, 2) 6 | print(calculos.media()) 7 | -------------------------------------------------------------------------------- /modulos-em-python/6_modulo_em_outro_diretorio_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 6 3 | import meus_modulos 4 | 5 | calculos = meus_modulos.Calculos(3, 2) 6 | print(calculos.media()) 7 | -------------------------------------------------------------------------------- /geradores-em-python/um_elemento_por_vez.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | texto = "um elemento por vez" 4 | 5 | for i in texto: 6 | print(i + "/", end="") 7 | 8 | print() 9 | -------------------------------------------------------------------------------- /modulos-em-python/5_modulo_em_outro_diretorio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 5 3 | from meus_modulos import calculos 4 | 5 | calculos = calculos.Calculos(3, 2) 6 | print(calculos.media()) 7 | -------------------------------------------------------------------------------- /um-basico-de-pytest/programa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from medias import media_aritmetica 5 | 6 | print(media_aritmetica([])) 7 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/interlac.bas: -------------------------------------------------------------------------------- 1 | 10 COLOR 15,0,0 2 | 20 SCREEN 8,,,,,,2:VDP(10)=VDP(10) AND &H7F 3 | 30 FOR I%=0 TO 1:SET PAGE I%,I% 4 | 40 BLOAD "REDUCED.S8"+CHR$(48+I%),S 5 | 50 NEXT I% 6 | 60 K$=INPUT$(1) -------------------------------------------------------------------------------- /registro-de-eventos-em-python/programa_de_teste.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | 5 | for i in range(1,9): 6 | print('+' * i, ' ', end='' if i < 8 else '\n') 7 | -------------------------------------------------------------------------------- /um-basico-de-pytest/alunos.json: -------------------------------------------------------------------------------- 1 | [{"nome":"Adão Nogueira","notas":[9.89,8.75,6.34,8.05]},{"nome":"Bruno Tavares","notas":[]},{"nome":"João da Silva","notas":[5.1,5.22,7.33,8]},{"nome":"Jose Queiroz","notas":[9.31,7.9,8,8.832]}] 2 | -------------------------------------------------------------------------------- /modulos-em-python/calculos.py: -------------------------------------------------------------------------------- 1 | class Calculos(object): 2 | a=0 3 | b=0 4 | def __init__(self, a, b): 5 | self.a = a 6 | self.b = b 7 | 8 | def media(self): 9 | return (self.a + self.b)/2.0 10 | -------------------------------------------------------------------------------- /modulos-em-python/7_modulo_carregado_em_tmp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 7 3 | import sys 4 | sys.path.append('/tmp') 5 | 6 | import meus_modulos 7 | 8 | calculos = meus_modulos.Calculos(3, 2) 9 | print(calculos.media()) 10 | -------------------------------------------------------------------------------- /modulos-em-python/meus_modulos/calculos.py: -------------------------------------------------------------------------------- 1 | class Calculos(object): 2 | a=0 3 | b=0 4 | def __init__(self, a, b): 5 | self.a = a 6 | self.b = b 7 | 8 | def media(self): 9 | return (self.a + self.b)/2.0 10 | -------------------------------------------------------------------------------- /convertendo-imagens-para-o-atari-st/reading.py: -------------------------------------------------------------------------------- 1 | from divisiblelist import DivisibleList 2 | from PIL import Image 3 | 4 | from degas import load_pic 5 | 6 | filename = "cosmotro.pi1" # "montain.pi3" 7 | 8 | picture = load_pic(filename) 9 | picture.show() 10 | -------------------------------------------------------------------------------- /registro-de-eventos-em-python/registro_em_arquivo.log: -------------------------------------------------------------------------------- 1 | 2018-09-22 12:13:55,173 DEBUG: Iniciando o programa. 2 | 2018-09-22 12:13:55,173 DEBUG: Finalizando o programa. 3 | 2018-09-22 12:37:18,536 DEBUG: Iniciando o programa. 4 | 2018-09-22 12:37:18,536 DEBUG: Finalizando o programa. 5 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/status.json: -------------------------------------------------------------------------------- 1 | {"format":1,"version":"4.5.2","settings":"d36601c4f22db23c5294345f5ba388d8","files":{"pode_beber_py":{"hash":"33df666992b54d119345b40a6c701c7e","index":{"nums":[1,13,2,0,0,0,0],"html_filename":"pode_beber_py.html","relative_filename":"pode_beber.py"}}}} -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/LOADER5.BAS: -------------------------------------------------------------------------------- 1 | 10 COLOR 15,0,0:SCREEN 5 2 | 15 F$="SAMPLE.P5" 3 | 20 VDP(1)=VDP(1) AND &HBF 4 | 25 VDP(9)=VDP(9) OR &H20 5 | 30 BLOAD F$+"L",S,30336! 6 | 35 COLOR=RESTORE 7 | 40 BLOAD F$+"0",S 8 | 45 VDP(10)=VDP(10) AND &H7F 9 | 50 VDP(1)=VDP(1) OR &H40 10 | 55 K$=INPUT$(1) 11 |  -------------------------------------------------------------------------------- /orientacao-a-objetos-em-ruby-o-basico/Supernome.rb: -------------------------------------------------------------------------------- 1 | # -*- mode: ruby -*- 2 | # vi: set ft=ruby : 3 | 4 | require './Nome.rb' 5 | 6 | class Supernome < Nome 7 | 8 | # método que escreve o nome completo de outra forma 9 | def escreve_nome_completo 10 | @sobrenome.upcase+", "+@nome 11 | end 12 | 13 | end 14 | -------------------------------------------------------------------------------- /usando-o-pydantic/exemplo_com_um_livro.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Exemplo com o uso a primeira versão da classe 'Book' 3 | e um único livro.""" 4 | import json 5 | 6 | from books.models import BookBase as Book 7 | 8 | 9 | data = json.load(open("livros.json", "r")) 10 | book = Book(**data[0]) 11 | 12 | print(book.json(indent=4)) 13 | -------------------------------------------------------------------------------- /modulos-em-python/3_classe_dentro_do_programa.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # exemplo 3 3 | class Calculos(object): 4 | a=0 5 | b=0 6 | def __init__(self, a, b): 7 | self.a = a 8 | self.b = b 9 | 10 | def media(self): 11 | return (self.a + self.b)/2.0 12 | 13 | calculos = Calculos(3, 2) 14 | print(calculos.media()) 15 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/colorido.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from module.colors import TangoColors 3 | from module.decorators import marker2 4 | 5 | tango = TangoColors() 6 | 7 | 8 | @marker2(tango.sky[2], tango.orange[1]) 9 | def greetings() -> str: 10 | """ 11 | Retorna um "Olá mundo!" 12 | """ 13 | return " Olá mundo! " 14 | 15 | 16 | print(greetings()) 17 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-2/tratando_o_raise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | 6 | try: 7 | print('Aguarde 5 segundos para a exceção...') 8 | sleep(5) 9 | raise ValueError 10 | except: 11 | print('Ocorreu uma exceção:') 12 | raise 13 | print('Esta mensagem não será impressa.') 14 | -------------------------------------------------------------------------------- /argumentos-de-funcoes-em-python/concat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | 5 | def concat(*args): 6 | """ Concatena todas as strings passadas para a função """ 7 | return ''.join([i for i in args]) 8 | 9 | 10 | if __name__ == '__main__': 11 | print(concat('a', 'b', 'c')) 12 | print(concat('caixa', ' ', 'de', ' ', 'madeira')) 13 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/LOADER7.BAS: -------------------------------------------------------------------------------- 1 | 10 COLOR 15,0,0:SCREEN 7,,,,,2 2 | 15 F$="SAMPLE.P7" 3 | 20 VDP(1)=VDP(1) AND &HBF 4 | 25 VDP(9)=VDP(9) OR &H20 5 | 30 BLOAD F$+"L",S,64128! 6 | 35 COLOR=RESTORE 7 | 40 FOR I%=0 TO 1:SET PAGE I%,I% 8 | 45 BLOAD F$+CHR$(48+I%),S 9 | 50 NEXT I% 10 | 55 VDP(10)=VDP(10) AND &H7F 11 | 60 VDP(1)=VDP(1) OR &H40 12 | 65 K$=INPUT$(1):SCREEN ,,,,,0 13 |  -------------------------------------------------------------------------------- /mais-decoradores-em-python/simples.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from module.decorators import marker 3 | 4 | 5 | @marker 6 | def mesg(text: str) -> str: 7 | """ 8 | Retorna uma 'string' em caixa alta. 9 | """ 10 | return text.upper() 11 | 12 | 13 | print( 14 | "Este texto é normal.", 15 | mesg("Mas este precisa ser marcado."), 16 | "E este aqui é normal também.", 17 | sep="\n", 18 | ) 19 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/create_worksheet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from random import randint 3 | 4 | from openpyxl import Workbook 5 | 6 | RAND = (1, 100) 7 | ROWS, COLS = 10, 10 8 | 9 | wb = Workbook() 10 | ws = wb.active 11 | 12 | for r in range(1, ROWS + 1): 13 | for c in range(1, COLS + 1): 14 | ws.cell(row=r, column=c, value=randint(*RAND)) 15 | 16 | ws.title = "Aleatório" 17 | wb.save("aleatórios.xlsx") 18 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = false 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | 8 | [*.py] 9 | indent_size = 4 10 | indent_style = space 11 | insert_final_newline = true 12 | trim_trailing_whitespace = true 13 | 14 | [*.bas] 15 | charset = latin1 16 | insert_final_newline = false 17 | end_of_line=crlf 18 | indent_style = space 19 | ident_size = tab 20 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/argumentos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from module.decorators import marker2 3 | 4 | 5 | @marker2(fore=(255, 255, 255), back=(0, 0, 255)) 6 | def mesg(text: str) -> str: 7 | """ 8 | Retorna uma 'string' em caixa alta. 9 | """ 10 | return text.upper() 11 | 12 | 13 | print( 14 | "Este texto é normal.", 15 | mesg("Mas este precisa ser marcado."), 16 | "E este aqui é normal também.", 17 | sep="\n", 18 | ) 19 | -------------------------------------------------------------------------------- /usando-o-pydantic/exemplo_com_muitos_livros.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Exemplo com a versão final das classes 'Book' e 'Shelf'.""" 3 | import json 4 | 5 | from books.models import BookV2 as Book 6 | from books.models import ShelfV2 as Shelf 7 | 8 | 9 | data = json.load(open("livros.json", "r")) 10 | books = [Book(**book) for book in data] 11 | 12 | shelf = Shelf(id="d09722d7-a92d-4e79-a972-7b4712abe2c3", books=books) 13 | 14 | print(shelf.json(indent=4)) 15 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | contador += 1 14 | sleep(.03125) # espera 1/32 segundos. 15 | 16 | print(" FIM!") 17 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/multiplica.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from typing import Callable 3 | 4 | from module.decorators import multiply 5 | 6 | # o valor inicial de 7 | f = 2 8 | 9 | 10 | @multiply(f) 11 | def to_float(i) -> float: 12 | """ 13 | Converte um nome em `i` para ponto flutuante. 14 | """ 15 | return float(i) 16 | 17 | 18 | if __name__ == "__main__": 19 | print(to_float(4)) 20 | f += 1 # não vai funcionar 21 | print(to_float(4)) 22 | -------------------------------------------------------------------------------- /um-outro-exemplo-de-angularjs/exemplo-abj-2.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "nome": "Adão Nogueira", 3 | "notas": [ 4 | 9.89, 5 | 8.75, 6 | 6.34, 7 | 8.05 8 | ] 9 | }, { 10 | "nome": "Bruno Tavares", 11 | "notas": [ 12 | 6.32, 13 | 8.25, 14 | 7.67, 15 | 7.97 16 | ] 17 | }, { 18 | "nome": "João da Silva", 19 | "notas": [ 20 | 5.1, 21 | 5.22, 22 | 7.33, 23 | 8 24 | ] 25 | }, { 26 | "nome": "José Queiroz", 27 | "notas": [ 28 | 9.31, 29 | 7.9, 30 | 8, 31 | 8.832 32 | ] 33 | }] 34 | -------------------------------------------------------------------------------- /xml-em-perl-parte-3/ped.ptxt: -------------------------------------------------------------------------------- 1 | HISTÓRICO DE EXERCÍCIOS 2 | Exercícios : %_WORKOUTS_% 3 | Maior distância : %_FARTHEST_% km 4 | Distância total : %_RUNDISTANCE_% km 5 | Tempo total : %_TOTALHOU_%h %_TOTALMIN_%m %_TOTALSEC_%s 6 | Calorias : %_CALORIES_% 7 | Número de passos : %_TOTALSTEPS_% 8 | Caminhando : %_WALKING_% 9 | Correndo : %_RUNNING_% 10 | Passadas : ~%_MYSTEPS_% m 11 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/quantization.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from PIL import Image 3 | 4 | from functions import count_colors, quantize_colors 5 | 6 | image = Image.open("sample_256x192.png") 7 | 8 | # cria a tabela de frequência de cores 9 | colors = count_colors(image) 10 | 11 | # monta a paleta de 16 cores para a imagem 12 | palette = quantize_colors(colors, 16) 13 | 14 | # imprime relação das cores em hexadecimal... 15 | print("\n".join((f"#{r:02x}{g:02x}{b:02x}" for r, g, b in palette))) 16 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-3/minha_excecao.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class MinhaExcecaoError(Exception): 6 | pass 7 | 8 | 9 | try: 10 | erro = False 11 | 12 | # lista de comandos que mudarão o estado de 'erro' --> 13 | erro = True 14 | # <-- lista de comandos que mudarão o estado de 'erro' 15 | 16 | if erro: 17 | raise MinhaExcecaoError("Ocorreu um erro!") 18 | 19 | except MinhaExcecaoError as mensagem: 20 | print(mensagem) 21 | exit(1) 22 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-b.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | if contador == 25: 14 | comando_inexistente 15 | contador += 1 16 | sleep(.03125) # espera 1/32 segundos. 17 | 18 | print(" FIM!") 19 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-python-o-basico/nome.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from nomes import Nome, Supernome 5 | 6 | ''' define os novos objetos ''' 7 | giovanni=Supernome("Giovanni","Nunes") 8 | 9 | ''' usará automaticamente o __str__ ''' 10 | print("O primeiro nome é {}.".format(giovanni)) 11 | 12 | ''' usará explicitamente um dos métodos ''' 13 | print("E {} e nome completo.".format(giovanni.escreve_nome_completo())) 14 | 15 | ''' o que tem dentro da classe? ''' 16 | print(giovanni) 17 | 18 | exit 19 | -------------------------------------------------------------------------------- /um-basico-de-pytest/alunos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from json import loads 5 | from medias import media_aritmetica 6 | 7 | alunos = loads(open('alunos.json', 'r').read()) 8 | 9 | for aluno in alunos: 10 | nome, notas = aluno.items() 11 | print('{}\t'.format(aluno.get('nome')), end='') 12 | media = media_aritmetica(aluno.get('notas')) 13 | if media is not None: 14 | print('{:.3f}'.format(media)) 15 | else: 16 | print('sem notas') 17 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-ruby-o-basico/Nome.rb: -------------------------------------------------------------------------------- 1 | # -*- mode: ruby -*- 2 | # vi: set ft=ruby : 3 | 4 | class Nome 5 | attr_accessor :nome, :sobrenome 6 | 7 | # construtor da classe 8 | def initialize(nome,sobrenome) 9 | @nome=nome 10 | @sobrenome=sobrenome 11 | end 12 | 13 | # método padrão para "escrever" o conteúdo 14 | def to_s 15 | @nome 16 | end 17 | 18 | # método que escreve o nome completo 19 | def escreve_nome_completo 20 | @nome+" "+@sobrenome 21 | end 22 | 23 | end 24 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/read_csv_file_as_dict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Lê um arquivo CSV para um dicionário. 4 | """ 5 | from csv import DictReader 6 | from json import dumps 7 | 8 | # arquivo de entrada 9 | STUDENTS_FILE = "students.csv" 10 | 11 | if __name__ == "__main__": 12 | 13 | # carrega todas as linhas do arquivo CSV 14 | with open(STUDENTS_FILE, "r") as f: 15 | students = [record for record in DictReader(f)] 16 | 17 | # imprime apenas o nono registro 18 | print(dumps(students[8], indent=4)) 19 | -------------------------------------------------------------------------------- /registro-de-eventos-em-python/registro_em_disco.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | import logging 5 | 6 | logging.basicConfig(filename='registro_em_arquivo.log', 7 | level=logging.DEBUG, 8 | format='%(asctime)s %(levelname)s: %(message)s') 9 | 10 | logging.debug('Iniciando o programa.') 11 | 12 | for i in range(1,9): 13 | print('+' * i, ' ', end='' if i < 8 else '\n') 14 | 15 | logging.debug('Finalizando o programa.') 16 | 17 | logging.shutdown() 18 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/read_csv_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Lê arquivo CSV. 4 | """ 5 | from csv import reader 6 | 7 | # arquivo de entrada 8 | STUDENTS_FILE = "students.csv" 9 | 10 | if __name__ == "__main__": 11 | 12 | # carrega todas as linhas do arquivo CSV 13 | with open(STUDENTS_FILE, "r") as f: 14 | students = [record for record in reader(f)] 15 | 16 | # imprime as duas primeiras colunas de cada registro 17 | for student in students[1:]: 18 | print("{0:03d} : {1}".format(int(student[0]), student[1])) 19 | -------------------------------------------------------------------------------- /geradores-em-python/cria_diretorios.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | let contador=1 4 | 5 | arquivo="arquivo" 6 | ext="txt" 7 | 8 | cria_arquivo() { 9 | echo "Criando: $dir/$1" 10 | touch $1 11 | } 12 | 13 | for dir in "abc" "def" "ghi"; do 14 | mkdir $dir 15 | cd $dir 16 | 17 | for j in {0..1}; do 18 | cria_arquivo $arquivo-$contador.$ext 19 | let contador++ 20 | 21 | if (( contador > 5 )); then 22 | ext="html" 23 | fi 24 | done 25 | 26 | [[ $dir == "def" ]] && cria_arquivo .ignore 27 | cd .. 28 | done 29 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-ruby-o-basico/nome.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | # as duas classes serão carregadas 6 | require './Supernome.rb' 7 | 8 | # define o novo objeto 9 | giovanni=Nome.new('Giovanni','Nunes') 10 | # giovanni=Supernome.new('Giovanni','Nunes') 11 | 12 | # usará automaticamente o .to_s 13 | puts "O primeiro nome é %s." % giovanni 14 | 15 | # usará explicitamente um dos métodos 16 | puts "E %s o nome completo do sujeito." % giovanni.escreve_nome_completo 17 | 18 | # o que tem dentro da classe? 19 | puts giovanni 20 | 21 | exit 22 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/reducing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from PIL import Image 3 | 4 | from functions import count_colors, quantize_colors, reduce_colors 5 | 6 | image = Image.open("sample_256x192.png") 7 | 8 | # recupera a lista de cores 9 | colors = count_colors(image) 10 | 11 | # cria a tabela de frequência de cores 12 | palette = quantize_colors(colors, 16) 13 | 14 | # converte uma dada imagem para 16 cores sem alicar dithering 15 | __ = reduce_colors(image, palette, dither=False) 16 | 17 | # exibe a imagem convertida, use ".save()" para salvá-la em arquivo... 18 | image.show() 19 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | try: 14 | if contador == 25: 15 | comando_inexistente 16 | except: 17 | print("<<\nexceção interceptada\n>>", end="") 18 | contador += 1 19 | sleep(.03125) # espera 1/32 segundos. 20 | 21 | print(" FIM!") 22 | -------------------------------------------------------------------------------- /decoradores-em-python/notas.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "id": 1, 3 | "nome": "Adão Nogueira", 4 | "nota_1": 9.89, 5 | "nota_2": 8.75, 6 | "nota_3": 6.34, 7 | "nota_4": 8.05 8 | }, 9 | { 10 | "id": 2, 11 | "nome": "Bruno Tavares", 12 | "nota_1": 6.32, 13 | "nota_2": 8.25, 14 | "nota_3": 7.67, 15 | "nota_4": 7.97 16 | }, 17 | { 18 | "id": 3, 19 | "nome": "João da Silva", 20 | "nota_1": 5.1, 21 | "nota_2": 5.22, 22 | "nota_3": 7.33, 23 | "nota_4": 8 24 | }, 25 | { 26 | "id": 4, 27 | "nome": "José Queiroz", 28 | "nota_1": 9.31, 29 | "nota_2": 7.9, 30 | "nota_3": 8, 31 | "nota_4": 8.832 32 | } 33 | ] -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/couting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from PIL import Image 3 | 4 | from functions import count_colors 5 | 6 | image = Image.open("sample_256x192.png") 7 | 8 | # cria a tabela de frequência de cores 9 | counter = count_colors(image) 10 | 11 | # cria uma lista contendo cor e sua frequência 12 | colors = sorted( 13 | [("#{:02x}{:02x}{:02x}".format(*c), q) for c, q in counter], 14 | key=lambda i: i[1], 15 | reverse=True, 16 | ) 17 | 18 | # imprime o resultado na tela... 19 | print("\n".join("{} {:5d}".format(*c) for c in colors)) 20 | print("total de cores = {}".format(len(colors))) 21 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-b_while.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | try: 11 | while contador < 100: 12 | print(".", end="") 13 | stdout.flush() # força a atualização da tela. 14 | if contador == 25: 15 | comando_inexistente 16 | contador += 1 17 | sleep(.03125) # espera 1/32 segundos. 18 | except: 19 | print("<<\nexceção interceptada\n>>", end="") 20 | 21 | print(" FIM!") 22 | -------------------------------------------------------------------------------- /decoradores-em-python/funcao_como_objeto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Exemplo de função sendo atribuída a uma variável. 5 | """ 6 | from __future__ import print_function 7 | 8 | 9 | def minha_funcao(i, j): 10 | """ Recebe dois valores em `i` e `j` e retorna a soma entre eles. """ 11 | return i + j 12 | 13 | 14 | def main(): 15 | """ Função principal """ 16 | print("*** minha_funcao() ***") 17 | print(minha_funcao(2, 3)) 18 | 19 | outra_funcao = minha_funcao 20 | 21 | print("*** outra_funcao() ***") 22 | print(outra_funcao(2, 3)) 23 | 24 | 25 | if __name__ == "__main__": 26 | main() 27 | -------------------------------------------------------------------------------- /um-outro-exemplo-de-angularjs/exemplo-abj-2.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family:'Titillium Web',Sans; 3 | } 4 | 5 | .jumbotron { 6 | background-image:url('https://farm8.staticflickr.com/7341/11696773813_bccec7b286_o_d.jpg'); 7 | background-position:center; 8 | background-repeat: no-repeat; 9 | background-size: cover; 10 | margin-top:0.5em; 11 | text-align:center; 12 | } 13 | 14 | .jumbotron h1 { 15 | color: #ffffff; 16 | font-weight: bold; 17 | text-shadow: 0 0 2px #000000; 18 | } 19 | 20 | .jumbotron p { 21 | color: #ffffff; 22 | } 23 | 24 | .footer { 25 | padding-top: 40px; 26 | padding-bottom: 40px; 27 | margin-top: 40px; 28 | border-top: 1px solid #eee; 29 | } 30 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-python-alem-do-basico/veiculos.py: -------------------------------------------------------------------------------- 1 | """ 2 | Veículos 3 | """ 4 | 5 | 6 | class Veiculo: 7 | """ 8 | Classe de testes implementando accessors (getters e setters) 9 | """ 10 | 11 | def __init__(self, modelo: str, cor: str) -> None: 12 | self.__modelo = modelo 13 | self.__cor = cor 14 | 15 | def __str__(self) -> str: 16 | return f"{self.modelo} {self.cor}" 17 | 18 | @property 19 | def modelo(self) -> str: 20 | return self.__modelo 21 | 22 | @property 23 | def cor(self) -> str: 24 | return self.__cor 25 | 26 | @cor.setter 27 | def cor(self, cor) -> None: 28 | self.__cor = cor 29 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-d.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | try: 14 | if contador == 50: 15 | comando_inexistente 16 | elif contador == 25: 17 | limite += contador * 2 18 | except: 19 | print("<<\nexceção interceptada\n>>", end="") 20 | contador += 1 21 | sleep(.03125) # espera 1/32 segundos. 22 | 23 | print(" FIM!") 24 | -------------------------------------------------------------------------------- /exemplo-com-angularjs-bootstrap-e-jquery/exemplo-abj.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family:'Raleway','Sans'; 3 | } 4 | 5 | .jumbotron { 6 | background-image:url('https://farm4.staticflickr.com/3678/11779170364_2d49a9c51d_o_d.jpg'); 7 | background-position:center; 8 | background-repeat: no-repeat; 9 | background-size: cover; 10 | margin-top:0.5em;; 11 | text-align:center; 12 | 13 | } 14 | 15 | .jumbotron h1 { 16 | color: #ffffff; 17 | font-weight: bold; 18 | text-shadow: 0 0 2px #000000; 19 | } 20 | 21 | .jumbotron p { 22 | color: #ffffff; 23 | } 24 | 25 | .footer { 26 | padding-top: 40px; 27 | padding-bottom: 40px; 28 | margin-top: 40px; 29 | border-top: 1px solid #eee; 30 | } 31 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-e.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | try: 14 | if contador == 25: 15 | comando_inexistente 16 | elif contador == 50: 17 | limite = int("abc") 18 | except NameError: 19 | print("<<\nexceção interceptada\n>>", end="") 20 | contador += 1 21 | sleep(.03125) # espera 1/32 segundos. 22 | 23 | print(" FIM!") 24 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-2/salva_arquivo-a.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from random import randint 5 | from sys import argv 6 | 7 | nome_do_arquivo = argv[1] 8 | dados = "".join([chr(randint(32, 126)) for i in range(65536)]) 9 | 10 | try: 11 | status = 0 12 | with open(nome_do_arquivo, 'w') as f: 13 | f.write(dados) 14 | except IOError: 15 | print('Impossível escrever os dados em `{}`' 16 | .format(nome_do_arquivo)) 17 | status = 2 18 | else: 19 | print('Arquivo salvo com sucesso!') 20 | finally: 21 | if status > 0: 22 | exit(status) 23 | 24 | print("Faz outras coisas e depois termina.") 25 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/retrieve_worksheet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from colorama import Back, Fore, init 3 | from openpyxl import load_workbook 4 | 5 | ROWS, COLS = 10, 10 6 | WORKBOOK, WORKSHEET = "aleatórios.xlsx", "Aleatório" 7 | 8 | wb = load_workbook(WORKBOOK) 9 | ws = wb[wb.sheetnames[0]] # WORKSHEET] 10 | 11 | for r in range(1, ROWS + 1): 12 | print( 13 | Fore.CYAN if r % 2 else Fore.MAGENTA, 14 | " | ".join( 15 | ( 16 | "{:5d}".format( 17 | ws.cell(row=r, column=c).value 18 | ) 19 | for c in range(1, COLS + 1) 20 | ) 21 | ), 22 | Fore.RESET, 23 | sep="", 24 | ) 25 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/convert_csv_to_xlsx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from csv import reader 3 | 4 | from openpyxl import Workbook 5 | from openpyxl.utils.cell import get_column_letter 6 | 7 | STUDENTS = "students" 8 | 9 | width = {} 10 | 11 | wb = Workbook() 12 | ws = wb.active 13 | 14 | with open(STUDENTS + ".csv", "r") as f: 15 | for r, student in enumerate(reader(f), start=1): 16 | for c, data in enumerate(student, start=1): 17 | ws.cell(row=r, column=c, value=data) 18 | width[c] = max((width.get(c, 0), len(data))) 19 | 20 | for c, size in width.items(): 21 | ws.column_dimensions[get_column_letter(c)].width = 1 + size 22 | 23 | ws.title = STUDENTS 24 | wb.save(STUDENTS + ".xlsx") 25 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-python-o-basico/nomes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | class Nome(object): 5 | 6 | def __init__(self,nome,sobrenome): 7 | ''' método construtor da classe ''' 8 | self.nome = nome 9 | self.sobrenome = sobrenome 10 | def __str__(self): 11 | ''' método para 'escrever' o conteúdo ''' 12 | return self.nome 13 | 14 | def escreve_nome_completo(self): 15 | ''' método que escreve o nome completo ''' 16 | return self.nome+" "+self.sobrenome 17 | 18 | class Supernome(Nome): 19 | 20 | def escreve_nome_completo(self): 21 | ''' método que escreve o nome completo de outra forma ''' 22 | return self.sobrenome.upper()+", "+self.nome 23 | -------------------------------------------------------------------------------- /um-basico-de-pytest/medias.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | def media_aritmetica(valores): 5 | """ Calcula a média aritmética de uma lista de números passada em 6 | `valores`, retorna a média ou então None caso não a lista esteja 7 | vazia. """ 8 | quantidade = len(valores) 9 | if quantidade: 10 | return sum(valores) / quantidade 11 | else: 12 | return False 13 | 14 | class TestMedias: 15 | def test_media_com_lista_numerica(self): 16 | """ Valida o cálculo da média. """ 17 | assert media_aritmetica([1, 1]) == 1.0 18 | 19 | def test_media_com_lista_vazia(self): 20 | """ Valida o envio de 'None' para listas vazias. """ 21 | assert media_aritmetica([]) == None 22 | -------------------------------------------------------------------------------- /usando-grupos-em-expressoes-regulares/lorem_ipsum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | 5 | if __name__ == '__main__': 6 | 7 | # lê o arquivo com a versão em HTML do _lorem ipsum_ 8 | lorem_ipsum = open('lorem_ipsum.html').read() 9 | 10 | print('Texto emtre ...:') 11 | 12 | # se for usado apenas uma vez, é possível fazer direto 13 | for i in re.findall('(.+)', lorem_ipsum): 14 | print('\t- ' + i ) 15 | 16 | print('\nTexto entre ...:') 17 | 18 | # mas se usar mais de uma vez, compensa criar uma variável. 19 | italizado = re.compile('(.+)') 20 | 21 | for i in italizado.findall(lorem_ipsum): 22 | print('\t- ' + i) 23 | 24 | print('') 25 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/write_csv_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Escreve arquivo CSV. 4 | """ 5 | from csv import writer 6 | from random import uniform 7 | 8 | # arquivo de saída 9 | GRADES_FILE = "grades.csv" 10 | 11 | # cabeçalho do arquivo CSV 12 | HEADER = ["id", "nota1", "nota2"] 13 | 14 | if __name__ == "__main__": 15 | 16 | # gera números aleatórios com duas casas decimais 17 | grade = lambda: round(uniform(0.0, 10.0), 2) 18 | 19 | # expressão geradora, cria 10 linhas 20 | data = ((i + 1, grade(), grade()) for i in range(10)) 21 | 22 | with open(GRADES_FILE, "w") as f: 23 | w = writer(f) 24 | # escreve o cabeçalho 25 | w.writerow(HEADER) 26 | # escreve todas as linhas 27 | w.writerows(data) 28 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-1/contar_ate_100-f.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | from sys import stdout 6 | 7 | print("Este programa contará até 100.") 8 | 9 | contador = 0 10 | while contador < 100: 11 | print(".", end="") 12 | stdout.flush() # força a atualização da tela. 13 | try: 14 | if contador == 25: 15 | comando_inexistente 16 | elif contador == 50: 17 | limite = int("abc") 18 | except NameError: 19 | print("<<\nexceção interceptada\n>>", end="") 20 | except ValueError: 21 | print("<<\noutra exceção aqui!\n>>", end="") 22 | contador += 1 23 | sleep(.03125) # espera 1/32 segundos. 24 | 25 | print(" FIM!") 26 | -------------------------------------------------------------------------------- /registro-de-eventos-em-python/segundo_exemplo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | import logging 5 | 6 | logging.basicConfig(level=logging.DEBUG, 7 | format='%(asctime)s %(levelname)s: %(message)s') 8 | 9 | logging.debug('Exibindo mensagem.') 10 | logging.info('Exibindo mensagem') 11 | logging.warning('Exibindo mensagem') 12 | logging.error('Exibindo mensagem') 13 | logging.critical('Exibindo mensagem') 14 | 15 | # apenas as duas últimas linh 16 | logging.disable(logging.WARNING) 17 | 18 | logging.debug('Não exibindo mensagem.') 19 | logging.info('Não exibindo mensagem') 20 | logging.warning('Não exibindo mensagem') 21 | logging.error('Não exibindo mensagem') 22 | logging.critical('Não exibindo mensagem') 23 | -------------------------------------------------------------------------------- /decoradores-em-python/funcao_como_argumento.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Exemplo de função sendo passada como argumento. 5 | """ 6 | from __future__ import print_function 7 | 8 | 9 | def minha_funcao(i, j): 10 | """ Recebe dois valores em `i` e `j` e retorna a soma entre eles. """ 11 | return i + j 12 | 13 | 14 | def outra_funcao(func, *args, **kwargs): 15 | """ Executa uma função `func` e duplica o valor. """ 16 | return func(*args, **kwargs) * 2 17 | 18 | 19 | def main(): 20 | """ Função principal """ 21 | print("*** minha_funcao() ***") 22 | print(minha_funcao(2, 3)) 23 | 24 | print("*** outra_funcao() ***") 25 | print(outra_funcao(minha_funcao, 2, 3)) 26 | 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /decoradores-em-python/funcao_decorada.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Exemplo de função sendo decorada via . 5 | """ 6 | from __future__ import print_function 7 | 8 | 9 | def decora_funcao(func): 10 | """ Decora a função `func` escrevendo '%%% agora decorada %%%'. """ 11 | 12 | def decoracao(): 13 | """ Função aninhada para decorar a função. """ 14 | print("%%% agora decorada %%%") 15 | func() 16 | 17 | return decoracao 18 | 19 | 20 | def main(): 21 | """ Função principal """ 22 | 23 | @decora_funcao 24 | def minha_funcao(): 25 | """ Apenas escreve '### minha_funcao() ###'. """ 26 | print("### minha_funcao() ###") 27 | 28 | minha_funcao() 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/jquery.ba-throttle-debounce.min.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery throttle / debounce - v1.1 - 3/7/2010 3 | * http://benalman.com/projects/jquery-throttle-debounce-plugin/ 4 | * 5 | * Copyright (c) 2010 "Cowboy" Ben Alman 6 | * Dual licensed under the MIT and GPL licenses. 7 | * http://benalman.com/about/license/ 8 | */ 9 | (function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this); 10 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/csv_as_variable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Manipula dados de CSV em variáveis e não arquivos. 4 | """ 5 | from csv import reader, writer 6 | from io import StringIO 7 | 8 | # este é o arquivo CSV falso 9 | fake_csv_file = ( 10 | "SP,São Paulo\n" 11 | + "RJ,Rio de Janeiro\n" 12 | + "ES,Espírito Santo\n" 13 | + "MG,Minas Gerais\n" 14 | ) 15 | 16 | if __name__ == "__main__": 17 | 18 | # cria dois opjetos StringIO 19 | input_file = StringIO(fake_csv_file) 20 | output_file = StringIO() 21 | 22 | # lê os dados do arquivo CSV e ordena. 23 | data = sorted(reader(input_file)) 24 | 25 | # prepara para gravar o arquivo CSV... 26 | w = writer(output_file) 27 | 28 | # ...e "grava" um falso arquivo CSV. 29 | w.writerows(data) 30 | 31 | print(output_file.getvalue()) 32 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-2/salva_arquivo-b.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from random import randint 5 | from sys import argv 6 | 7 | nome_do_arquivo = argv[1] 8 | 9 | dados = "".join([chr(randint(32, 126)) for i in range(65536)]) 10 | 11 | try: 12 | status = 0 13 | with open(nome_do_arquivo, 'w') as f: 14 | f.write(dados) 15 | except IOError as err: 16 | if 'Permission denied' in str(e): 17 | print('Você não pode criar arquivos aí!') 18 | status = 1 19 | else: 20 | print('Impossível escrever os dados em `{}`' 21 | .format(nome_do_arquivo)) 22 | status = 2 23 | else: 24 | print('Arquivo salvo com sucesso!') 25 | finally: 26 | if status > 0: 27 | exit(status) 28 | 29 | print("Faz outras coisas e depois termina.") 30 | -------------------------------------------------------------------------------- /decoradores-em-python/funcao_decorada_como_argumento.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Exemplo de função sendo decorada via passagem de argumento. 5 | """ 6 | from __future__ import print_function 7 | 8 | 9 | def decora_funcao(func): 10 | """ Decora a função `func` escrevendo '%%% agora decorada %%%'. """ 11 | 12 | def decoracao(): 13 | """ Função aninhada para decorar a função. """ 14 | print("%%% agora decorada %%%") 15 | func() 16 | 17 | return decoracao 18 | 19 | 20 | def main(): 21 | """ Função principal """ 22 | 23 | def minha_funcao(): 24 | """ Apenas escreve '### minha_funcao() ###'. """ 25 | print("### minha_funcao() ###") 26 | 27 | minha_funcao = decora_funcao(minha_funcao) 28 | 29 | minha_funcao() 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /criando-imagens-em-python/outro_teste_pillow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Teste do Pillow. 4 | """ 5 | from PIL import Image 6 | 7 | FILENAME = ("outro_teste_pillow.png", "PNG") 8 | 9 | # carrega o arquivo do primeiro exemplo 10 | pillow_obj = Image.open("teste_pillow.png") 11 | pixel_set = pillow_obj.load() 12 | 13 | # recupera as dimensões da imagem 14 | width = pillow_obj.width 15 | height = pillow_obj.height 16 | 17 | # laço só executa em 1/4 da imagem 18 | for row in range(height // 2): 19 | for col in range(width // 2): 20 | 21 | # recupera as cores atuai 22 | r, g, b = pixel_set[col, row] 23 | 24 | r //= 2 25 | 26 | # plota os pontos 27 | pixel_set[col, row] = (b, g, r) 28 | pixel_set[width - col - 1, height - row - 1] = (b, g, r) 29 | 30 | # salva o objeto como um arquivo PNG 31 | pillow_obj.save(*FILENAME) 32 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/join_student_and_grades.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Junta dois arquivos CSV criando um terceiro. 4 | """ 5 | from csv import reader, writer 6 | 7 | # oa arquivoso que serão lidos/criados 8 | STUDENTS_FILE = "students.csv" 9 | GRADES_FILE = "grades.csv" 10 | JOINED_FILE = "joined.csv" 11 | 12 | if __name__ == "__main__": 13 | 14 | # usa o 'with' para abrir todos os arquivos de uma vez 15 | with open(STUDENTS_FILE, "r") as sf, open(GRADES_FILE, "r") as gf, open( 16 | JOINED_FILE, "w" 17 | ) as jf: 18 | 19 | joined = writer(jf) 20 | students = reader(sf) 21 | grades = reader(gf) 22 | 23 | # lê uma linha de cada um dos arquivos de entrada... 24 | for student, grade in zip(students, grades): 25 | # ...junta e escreve no arquivo de saída 26 | joined.writerow(student + grade[1:]) 27 | -------------------------------------------------------------------------------- /argumentos-de-funcoes-em-python/argumentos.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import print_function 3 | 4 | 5 | def sem_argumentos(): 6 | return 1 7 | 8 | 9 | def um_argumento(i): 10 | return i + i 11 | 12 | 13 | def dois_argumentos(i, j): 14 | return i + j 15 | 16 | 17 | def argumentos_padrao(i, j=1): 18 | return i + j 19 | 20 | 21 | def argumentos_padrao_2(i, j=0, k=0): 22 | return i + j + k 23 | 24 | 25 | def todos_os_argumentos(*args): 26 | return sum(args) 27 | 28 | 29 | def alguns_argumentos(i, *args): 30 | return [i * j for j in args] 31 | 32 | 33 | def alguns_argumentos_com_padrao(i, *args, j=2): 34 | return [j + i * k for k in args] 35 | 36 | 37 | def argumentos_em_dicionario(**kargs): 38 | for k, v in kargs.items(): 39 | print('{} = {}'.format(k, v)) 40 | 41 | 42 | if __name__ == '__main__': 43 | print('Use \'from argumentos import *\' a partir do console do Python.') 44 | -------------------------------------------------------------------------------- /criando-imagens-em-python/teste_pillow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Teste do Pillow. 4 | """ 5 | from PIL import Image 6 | 7 | # dimensões da iimagem e nome do arquivo 8 | WIDTH, HEIGHT = 1024, 512 9 | FILENAME = ("teste_pillow.png", "PNG") 10 | 11 | # cria instância do Pillow 12 | pillow_obj = Image.new("RGB", (WIDTH, HEIGHT)) 13 | pixel_set = pillow_obj.load() 14 | 15 | # laço só executa em 1/4 da imagem 16 | for row in range(HEIGHT // 2): 17 | for col in range(WIDTH // 2): 18 | # define a cor no padrão RGB 19 | color = (row, abs(col - row), col) 20 | 21 | # calcula os pontos opostos... 22 | rev_col, rev_row = WIDTH - col - 1, HEIGHT - row - 1 23 | 24 | # plota os pontos 25 | pixel_set[col, row] = color 26 | pixel_set[rev_col, row] = color 27 | pixel_set[col, rev_row] = color 28 | pixel_set[rev_col, rev_row] = color 29 | 30 | # salva o objeto como um arquivo PNG 31 | pillow_obj.save(*FILENAME) 32 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/students.csv: -------------------------------------------------------------------------------- 1 | id,nome,endereço,bairro,cidade,uf,cep 2 | 1,Agatha da Costa,Via Cauã Rezende,Paraíso,da Mata,São Paulo,29093-532 3 | 2,Benício das Neves,"Rua de da Paz, 86",Capitão Eduardo,Pereira de Rodrigues,Rio de Janeiro,83392-182 4 | 3,Júlia da Paz,"Praia Moraes, 25",Conjunto Taquaril,Jesus de Goiás,Goiás,15319-202 5 | 4,Dr. Pedro Lucas Peixoto,"Esplanada Davi Luiz Freitas, 4",Virgínia,Pires de Minas,Distrito Federal,24123-321 6 | 5,Sophia Araújo,"Vila Beatriz Ramos, 125",Chácara Leonina,Lima,Minas Gerais,32024-590 7 | 6,Esther Freitas,"Pátio Fogaça, 52",Braúnas,da Rocha do Campo,Amapá,43302-598 8 | 7,Camila Rocha,"Fazenda Santos, 8",Serra,Correia das Flores,Santa Catarina,76917-907 9 | 8,Ana Júlia Porto,"Lagoa Sarah Moraes, 58",Monte São José,Lopes,Minas Gerais,82636-495 10 | 9,Pietra Campos,"Favela Natália Caldeira, 88",Xodo-Marize,Farias,Paraná,33447-453 11 | 10,João Felipe Carvalho,"Lago Davi Sales, 60",Renascença,Cunha,Mato Grosso do Sul,56446-679 12 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/students.csv: -------------------------------------------------------------------------------- 1 | id,nome,endereço,bairro,cidade,uf,cep 2 | 1,Agatha da Costa,Via Cauã Rezende,Paraíso,da Mata,São Paulo,29093-532 3 | 2,Benício das Neves,"Rua de da Paz, 86",Capitão Eduardo,Pereira de Rodrigues,Rio de Janeiro,83392-182 4 | 3,Júlia da Paz,"Praia Moraes, 25",Conjunto Taquaril,Jesus de Goiás,Goiás,15319-202 5 | 4,Dr. Pedro Lucas Peixoto,"Esplanada Davi Luiz Freitas, 4",Virgínia,Pires de Minas,Distrito Federal,24123-321 6 | 5,Sophia Araújo,"Vila Beatriz Ramos, 125",Chácara Leonina,Lima,Minas Gerais,32024-590 7 | 6,Esther Freitas,"Pátio Fogaça, 52",Braúnas,da Rocha do Campo,Amapá,43302-598 8 | 7,Camila Rocha,"Fazenda Santos, 8",Serra,Correia das Flores,Santa Catarina,76917-907 9 | 8,Ana Júlia Porto,"Lagoa Sarah Moraes, 58",Monte São José,Lopes,Minas Gerais,82636-495 10 | 9,Pietra Campos,"Favela Natália Caldeira, 88",Xodo-Marize,Farias,Paraná,33447-453 11 | 10,João Felipe Carvalho,"Lago Davi Sales, 60",Renascença,Cunha,Mato Grosso do Sul,56446-679 12 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/reducing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Converte uma imagem PNG de 256x192 reduzindo as cores. 4 | """ 5 | from PIL import Image 6 | 7 | from functions import bsave, reduce_color, to_msx2_rgb 8 | 9 | HEIGHT = 192 10 | WIDTH = 256 11 | 12 | if __name__ == "__main__": 13 | 14 | # carrega a image em PNG 15 | image = Image.open("sample_256x192.png") 16 | bitmap = image.load() 17 | 18 | # inicializa a "VRAM" 19 | vram = bytearray() 20 | 21 | for y in range(HEIGHT): 22 | for x in range(WIDTH): 23 | 24 | # extrai os componentes RGB e reduz os elementos de cpr 25 | old_pixel = bitmap[x, y] 26 | new_pixel = reduce_color(*old_pixel) 27 | 28 | # reflete a reduçãao de cores na imagem original 29 | bitmap[x, y] = new_pixel 30 | 31 | # adiciona o pixel ao 'array' 32 | vram.append(to_msx2_rgb(*new_pixel)) 33 | 34 | # salva a imagem 35 | image.save("reduced.png") 36 | bsave("reduced.sc8", vram) 37 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-php-o-basico/nome.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/php5 2 | 7 | 8 | This program is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 2 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | MA 02110-1301, USA. 22 | */ 23 | include('Nome.php'); 24 | $giovanni= new Nome('Giovanni','Nunes'); 25 | print $giovanni->escreveNomeCompleto()."\n"; 26 | ?> 27 | -------------------------------------------------------------------------------- /manipulando-xlsx-em-python/server.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from random import randint 3 | from tempfile import NamedTemporaryFile 4 | 5 | from flask import Flask, Response 6 | from openpyxl import Workbook 7 | from openpyxl.utils.cell import get_column_letter 8 | 9 | RAND = (1, 1000) 10 | ROWS, COLS = 100, 100 11 | 12 | DATE_FORMAT = "%Y%m%d_%H%M%S" 13 | 14 | HTTP_MIMETYPE_XLSX = ( 15 | "application/" "vnd.openxmlformats-officedocument." "spreadsheetml.sheet" 16 | ) 17 | 18 | app = Flask(__name__) 19 | 20 | 21 | @app.route("/ws/", methods=["GET"]) 22 | def worksheet(): 23 | 24 | wb = Workbook() 25 | ws = wb.active 26 | 27 | just_now = datetime.now() 28 | 29 | with NamedTemporaryFile() as xlsx: 30 | for row in range(1, ROWS + 1): 31 | for col in range(1, COLS + 1): 32 | ws["{}{}".format(get_column_letter(col), row)] = randint(*RAND) 33 | 34 | ws.title = just_now.strftime(DATE_FORMAT) 35 | wb.save(xlsx) 36 | 37 | xlsx.seek(0) 38 | 39 | return Response(xlsx.read(), mimetype=HTTP_MIMETYPE_XLSX) 40 | -------------------------------------------------------------------------------- /usando-o-pydantic/livros.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1, 4 | "title": "O MSX-DOS revelado", 5 | "subtitle": "Tudo a respeito do MSX-DOS que voc\\u00ea n\\u00e3o sabe e n\\u00e3o tinha a quem perguntar!", 6 | "author": "Ricardo Jurczyk Pinheiro", 7 | "publisher": "n/a", 8 | "pages": 240, 9 | "isbn": "9786599158100" 10 | }, 11 | { 12 | "id": 2, 13 | "title": "Texinfo", 14 | "subtitle": "The GNU Documentation Format", 15 | "author": "Robert J. Chassell, Richard M. Stallman", 16 | "publisher": "Free Software Foundation", 17 | "pages": 246, 18 | "isbn": "1882114671", 19 | "language": "English" 20 | }, 21 | { 22 | "id": 3, 23 | "title": "Programa\\u00e7\\u00e3o Shell Linux", 24 | "author": "J\\u00falio Cezar Neves", 25 | "publisher": "Brasport", 26 | "pages": 414, 27 | "isbn": "8574522031" 28 | }, 29 | { 30 | "id": 4, 31 | "title": "Python Fluente", 32 | "subtitle": "Programa\\u00e7\\u00e3o clara, concisa e eficaz", 33 | "author": "Luciano Ramalho", 34 | "publisher": "novatec", 35 | "pages": 800, 36 | "isbn": "9788575224625" 37 | } 38 | ] 39 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-python-alem-do-basico/computadores.py: -------------------------------------------------------------------------------- 1 | """ 2 | Computadores 3 | """ 4 | # sistemas operacionais disponíveis 5 | SISTEMAS = ( 6 | "Linux", 7 | "macOS", 8 | "Windows", 9 | "outros", 10 | ) 11 | 12 | 13 | class Computador: 14 | """ 15 | Classe de testes implementando `__slots__` 16 | """ 17 | 18 | __slots__ = ( 19 | "hostname", 20 | "sistema", 21 | "endereco", 22 | ) 23 | 24 | def __init__(self, hostname: str, so: int, ip: str) -> None: 25 | self.hostname = hostname 26 | self.sistema = SISTEMAS[so] 27 | self.endereco = ip or "127.0.0.1" 28 | 29 | def __str__(self) -> str: 30 | return "{host} ({os}) - {ip}".format( 31 | host=self.hostname, os=self.sistema, ip=self.endereco 32 | ) 33 | 34 | 35 | class Notebook(Computador): 36 | """ 37 | Classe que herda os atributos de uma classe com `__slots__`. 38 | """ 39 | 40 | __slots__ = "vpn" 41 | 42 | def __init__(self, hostname: str, so: int, ip: str, vpn: bool) -> None: 43 | self.vpn = vpn 44 | Computador.__init__(self, hostname, so, ip) 45 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/dithering.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Converte uma imagem PNG de 256x192 aplicando dithering. 4 | """ 5 | from PIL import Image 6 | 7 | from functions import add_noise, bsave, reduce_color, to_msx2_rgb 8 | 9 | HEIGHT = 192 10 | WIDTH = 256 11 | 12 | if __name__ == "__main__": 13 | 14 | # carrega a image em PNG 15 | image = Image.open("sample_256x192.png") 16 | bitmap = image.load() 17 | 18 | # inicializa a "VRAM" 19 | vram = bytearray() 20 | 21 | for y in range(HEIGHT): 22 | for x in range(WIDTH): 23 | 24 | # extrai os componentes RGB e reduz os elementos de cpr 25 | old_pixel = bitmap[x, y] 26 | new_pixel = reduce_color(*old_pixel) 27 | 28 | # reflete a reduçãao de cores na imagem original 29 | bitmap[x, y] = new_pixel 30 | 31 | # adiciona o pixel ao 'array' 32 | vram.append(to_msx2_rgb(*new_pixel)) 33 | 34 | # calcula a quantificação e apĺica nos vizinhos. 35 | error = [old - new for old, new in zip(old_pixel, new_pixel)] 36 | add_noise(bitmap, x, y, error) 37 | 38 | # salva a imagem 39 | image.save("dithered.png") 40 | bsave("dithered.sc8", vram) 41 | -------------------------------------------------------------------------------- /geradores-em-python/diretorio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ Exemplo de leitura de arquivos de diretórios. """ 3 | from os import listdir, path 4 | from fnmatch import fnmatch 5 | 6 | ME_IGNORE = ".ignore" 7 | FONTES = "*.txt" 8 | 9 | 10 | def recupera_arquivos(*lista_de_diretorios): 11 | """ (Gerador) Recupera os arquivos de uma lista de diretórios. Recebe a 12 | lista como uma tupla em `lista_de_diretorios` e retorna cada arquivo 13 | dentro deles. """ 14 | 15 | def verifica_diretorio(dirs): 16 | """ (Gerador) Verifica se o diretório existe e também se o arquivo 17 | que indica que ele deve ser ignorado existe. """ 18 | for diretorio in dirs: 19 | me_ignore = path.isfile(path.join(diretorio, ME_IGNORE)) 20 | if path.isdir(diretorio) and not me_ignore: 21 | yield diretorio 22 | 23 | for diretorio in verifica_diretorio(lista_de_diretorios): 24 | for arquivo in listdir(diretorio): 25 | if fnmatch(arquivo, FONTES): 26 | yield path.join(diretorio, arquivo) 27 | 28 | 29 | def main(): 30 | """ Função principal. """ 31 | for arquivo in recupera_arquivos("abc", "def", "ghi"): 32 | print("==> {}".format(arquivo)) 33 | 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-2/cavaleiro_negro.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import print_function 4 | from time import sleep 5 | import CavaleiroNegro 6 | 7 | print("\x1b[3J{}\x1b[2;1H".format(CavaleiroNegro.imprime())) 8 | 9 | for mensa in ["Ninguém passará! ", "Então você morrerá! ", 10 | "Não me afasto para ninguém. "]: 11 | sleep(.125) 12 | print(mensa) 13 | 14 | fala = 0 15 | while True: 16 | try: 17 | sleep(.25) 18 | if fala == 0: 19 | raise NameError 20 | elif fala == 1: 21 | raise TypeError 22 | elif fala == 2: 23 | raise ValueError 24 | elif fala == 3: 25 | raise ZeroDivisionError 26 | 27 | except NameError: 28 | print("Foi apenas um arranhão. ") 29 | except TypeError: 30 | print("Vamos, seu maricas! ") 31 | except ValueError: 32 | print("Oh, está amarelando, hem? ") 33 | except ZeroDivisionError: 34 | print("Covarde! Covarde! ") 35 | except KeyboardInterrupt: 36 | print("\nOk, considero um empate! ") 37 | break 38 | else: 39 | if fala < 12: 40 | print("Sou invencível! ") 41 | finally: 42 | fala += 1 43 | 44 | print("\x1b[24;1H", end="") 45 | exit(0) 46 | -------------------------------------------------------------------------------- /um-basico-de-orientacao-a-objetos-em-perl/nome.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # nome.pl 4 | # 5 | # Copyright 2015, Giovanni Nunes 6 | # 7 | # This program is free software; you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation; either version 2 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program; if not, write to the Free Software 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 20 | # MA 02110-1301, USA. 21 | # 22 | use strict; 23 | use Nome; 24 | 25 | print "Digite seu primeiro nome : "; 26 | my $n = ; 27 | chomp $n; 28 | 29 | print "Digite agora seu sobrenome : "; 30 | my $s = ; 31 | chomp $s; 32 | 33 | my $a=Nome->new($n,$s); 34 | 35 | print "\nOlá ".$a->escreveNomeCompleto()."!\n"; 36 | 37 | print "Ou devo usar apenas de ".$a->escreveNome()."?\n\n"; 38 | 39 | $a=Nome->DESTROY; 40 | 41 | exit 0; 42 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/interlacing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Converte uma imagem PNG de 256x384 aplicando dithering e entrelaçando. 4 | """ 5 | from PIL import Image 6 | 7 | from functions import add_noise, bsave, reduce_color, split_pages, to_msx2_rgb 8 | 9 | HEIGHT = 384 10 | WIDTH = 256 11 | 12 | if __name__ == "__main__": 13 | 14 | # carrega a image em PNG 15 | image = Image.open("sample_256x384.png") 16 | bitmap = image.load() 17 | 18 | # inicializa a "VRAM" 19 | vram = bytearray() 20 | 21 | for y in range(HEIGHT): 22 | for x in range(WIDTH): 23 | 24 | # extrai os componentes RGB e reduz os elementos de cpr 25 | old_pixel = bitmap[x, y] 26 | new_pixel = reduce_color(*old_pixel) 27 | 28 | # reflete a reduçãao de cores na imagem original 29 | bitmap[x, y] = new_pixel 30 | 31 | # adiciona o pixel ao 'array' 32 | vram.append(to_msx2_rgb(*new_pixel)) 33 | 34 | # calcula a quantificação e apĺica nos vizinhos. 35 | error = [old - new for old, new in zip(old_pixel, new_pixel)] 36 | add_noise(bitmap, x, y, error) 37 | 38 | # salva a imagem 39 | image.save("interlaced.png") 40 | 41 | image_0, image_1 = split_pages(vram) 42 | 43 | bsave("interlac.s80", image_0) 44 | bsave("interlac.s81", image_1) 45 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-php-o-basico/SuperNome.php: -------------------------------------------------------------------------------- 1 | 6 | 7 | This program is free software; you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation; either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 20 | MA 02110-1301, USA. 21 | */ 22 | 23 | include('Nome.php'); 24 | 25 | class SuperNome extends Nome 26 | { 27 | public $titulo; 28 | 29 | public function __construct($nome,$sobrenome,$titulo) 30 | { 31 | $this->nome = $nome; 32 | $this->sobrenome = $sobrenome; 33 | $this->titulo = $titulo; 34 | } 35 | 36 | public function escreveSuperNome() 37 | { 38 | return $this->titulo." ".$this->nome." ".$this->sobrenome; 39 | } 40 | }; 41 | ?> 42 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-javascript-o-basico/nome_ecma-262.js: -------------------------------------------------------------------------------- 1 | /* 2 | Versão utilizando a especificação da ECMA-262 3 | */ 4 | 5 | // permite a execução do código em Node.js 6 | "use strict"; 7 | 8 | // a classe 'Nome' 9 | class Nome { 10 | // construtor da classe 11 | constructor(nome,sobrenome){ 12 | this.nome = nome; 13 | this.sobrenome = sobrenome 14 | } 15 | // 'getter' que retorna apenas o nome 16 | get escreveNome(){ 17 | return this.nome; 18 | } 19 | // 'getter' que retorna o nome completo 20 | get escreveNomeCompleto(){ 21 | return this.nome + " " + this.sobrenome; 22 | } 23 | // 'setter' para armazenae o nome 24 | set armazenaNome(nome){ 25 | this.nome = nome; 26 | } 27 | } 28 | 29 | // a classe 'Supernome' 30 | class Supernome extends Nome { 31 | get escreveNomeCompleto(){ 32 | return this.sobrenome.toUpperCase() + ", "+ this.nome; 33 | } 34 | } 35 | 36 | // cria uma instância de 'Nome' 37 | var giovanni = new Nome("Giovanni","Nunes"); 38 | console.log("O primeiro nome é "+giovanni.escreveNome+"."); 39 | console.log("E "+giovanni.escreveNomeCompleto+" o nome completo."); 40 | 41 | // cria uma instância de 'Supernome' 42 | var giovanni2 = new Supernome("Giovanni","Nunes"); 43 | console.log("E "+giovanni2.escreveNomeCompleto+" o nome completo."); 44 | 45 | // e termina o programa 46 | return true; 47 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-javascript-o-basico/nome.js: -------------------------------------------------------------------------------- 1 | /* 2 | Versão não utilizando a especificação da ECMA-262 3 | */ 4 | 5 | // permite a execução do código em Node.js 6 | "use strict"; 7 | 8 | // a classe 'Nome' 9 | class Nome { 10 | // construtor da classe 11 | constructor(nome,sobrenome){ 12 | this.nome = nome; 13 | this.sobrenome = sobrenome 14 | } 15 | // define o 'getter' que retorna apenas o nome 16 | escreveNome(){ 17 | return this.nome; 18 | } 19 | // define o 'getter' que retorna o nome completo 20 | escreveNomeCompleto(){ 21 | return this.nome + " " + this.sobrenome; 22 | } 23 | // define o 'setter' para armazenae o nome 24 | armazenaNome(nome){ 25 | this.nome = nome; 26 | } 27 | } 28 | 29 | // a classe 'Supernome' 30 | class Supernome extends Nome { 31 | escreveNomeCompleto(){ 32 | return this.sobrenome.toUpperCase() + ", "+ this.nome; 33 | } 34 | } 35 | 36 | // cria uma instância de 'Nome' 37 | var giovanni = new Nome("Giovanni","Nunes"); 38 | console.log("O primeiro nome é "+giovanni.escreveNome()+"."); 39 | console.log("E "+giovanni.escreveNomeCompleto()+" o nome completo."); 40 | 41 | // cria uma instância de 'Supernome' 42 | var giovanni2 = new Supernome("Giovanni","Nunes"); 43 | console.log("E "+giovanni2.escreveNomeCompleto()+" o nome completo."); 44 | 45 | // e termina o programa 46 | return true; 47 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-php-o-basico/supernome.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/php5 2 | 7 | 8 | This program is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 2 of the License, or 11 | (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | MA 02110-1301, USA. 22 | */ 23 | include('SuperNome.php'); 24 | 25 | // Anakin é apenas um Jedi 26 | $jedi= new Nome('Anakin','Skywalker'); 27 | 28 | // Darth Vader tem uma posição no Império 29 | $sith= new SuperNome('Darth','Vader','Lord'); 30 | 31 | // Escrevo apenas os nomes 32 | print $jedi->escreveNomeCompleto()."\n"; 33 | print $sith->escreveNomeCompleto()."\n"; 34 | 35 | // Porém é bom lembrar quem Lord Vader é... :) 36 | print $sith->escreveSuperNome()."\n"; 37 | ?> 38 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-php-o-basico/Nome.php: -------------------------------------------------------------------------------- 1 | 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program; if not, write to the Free Software 18 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 | MA 02110-1301, USA. 20 | */ 21 | class Nome 22 | { 23 | public $nome; 24 | public $sobrenome; 25 | 26 | public function __construct($nome,$sobrenome) 27 | { 28 | $this->nome = $nome; 29 | $this->sobrenome = $sobrenome; 30 | } 31 | 32 | public function alteraNome($nome) 33 | { 34 | $this->nome=$nome; 35 | return true; 36 | } 37 | 38 | public function escreveNome() 39 | { 40 | return $this->nome; 41 | } 42 | 43 | public function escreveNomeCompleto() 44 | { 45 | return strtoupper($this->sobrenome).", ".$this->nome; 46 | } 47 | } 48 | ?> 49 | -------------------------------------------------------------------------------- /orientacao-a-objetos-em-python-alem-do-basico/pessoas.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pessoas 3 | """ 4 | from dataclasses import dataclass 5 | 6 | 7 | class Pessoa: 8 | """ 9 | Classe que implementa `__repr__` e `__str__`. 10 | """ 11 | 12 | ativo = False 13 | 14 | def __init__(self, nome: str, idade: int) -> None: 15 | self.nome = nome 16 | self.idade = idade 17 | 18 | def __repr__(self) -> str: 19 | return f"nome={self.nome}, idade={self.idade}, ativo={self.ativo}" 20 | 21 | def __str__(self) -> str: 22 | idade = "anos" if self.idade > 1 else "ano" 23 | ativo = "ativo" if self.ativo else "inativo" 24 | return f"{self.nome}, {self.idade} {idade} ({ativo})" 25 | 26 | 27 | class PessoaV2: 28 | """ 29 | Classe que inicializa `ativo` no método `__init__` replicando código. 30 | """ 31 | 32 | def __init__(self, nome: str, idade: int, ativo: bool = False) -> None: 33 | self.nome = nome 34 | self.idade = idade 35 | self.ativo = ativo 36 | 37 | 38 | class PessoaV3(Pessoa): 39 | """ 40 | Clase que inicializa `ativo` sen replicar código. 41 | """ 42 | 43 | def __init__(self, nome: str, idade: int, ativo: bool = False) -> None: 44 | self.ativo = ativo 45 | Pessoa.__init__(self, nome, idade) 46 | 47 | 48 | @dataclass 49 | class PessoaDataClass: 50 | """ 51 | Inicializa os atributos da classe de forma automática. 52 | """ 53 | 54 | pessoa: str 55 | idade: int 56 | ativo: bool = False 57 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/pode_beber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | IDADE_LEGAL = 18 5 | SUGESTAO = 'copo d\'água' 6 | 7 | 8 | def verifica_bebida(idade, bebida, alcool, sugestao=SUGESTAO): 9 | """ Verifica se a pessoa pode beber álcool de acordo com a idade. Recebe 10 | a idade em `idade` como inteiro, nome da bebibda em `bebida` como string, 11 | se esta possui álcool em `alcool` como booleano e sugestão em 'sugestao' 12 | como string (opcional). Retorna `True` e `bebida` se a idade for maior ou 13 | igual a permitida ou `False` e sugestão em caso contrário. """ 14 | if idade < IDADE_LEGAL and alcool: 15 | return False, sugestao 16 | else: 17 | return True, bebida 18 | 19 | 20 | class TestClass(object): 21 | """ Classe de testes para a função Verifica_bebida(). """ 22 | 23 | def test_maior_pede_cerveja(self): 24 | """ Testa se um maior de idade pode pedir uma cerveja. """ 25 | assert verifica_bebida(30, 'cerveja', True) == (True, 'cerveja') 26 | 27 | def test_menor_pede_cerveja(self): 28 | """ Testa se um menor de idade pode pedir uma cerveja. """ 29 | assert verifica_bebida(15, 'cerveja', True) == (False, SUGESTAO) 30 | 31 | def test_maior_pede_suco(self): 32 | """ Testa se um maior de idade pode pedir um suco. """ 33 | assert verifica_bebida(30, 'suco', False) == (True, 'suco') 34 | 35 | def test_menor_pede_suco(self): 36 | """ Testa se um menor de idade pode pedir um suco. """ 37 | assert verifica_bebida(15, 'suco', False) == (True, 'suco') 38 | -------------------------------------------------------------------------------- /um-basico-de-orientacao-a-objetos-em-perl/Nome.pm: -------------------------------------------------------------------------------- 1 | # 2 | # Nome.pm 3 | # 4 | # Copyright 2015, Giovanni Nunes 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program; if not, write to the Free Software 18 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 | # MA 02110-1301, USA. 20 | # 21 | package Nome; 22 | use strict; 23 | 24 | sub new 25 | { 26 | my ( $class ) = shift; 27 | my $self = { _nome => shift, _sobrenome => shift }; 28 | bless $self, $class; 29 | return $self; 30 | } 31 | 32 | sub alteraNome 33 | { 34 | my ( $self, $nome ) = @_; 35 | $self->{ _nome }=$nome; 36 | return $self; 37 | } 38 | 39 | sub escreveNomeCompleto 40 | { 41 | my ( $self ) = @_; 42 | return ( uc $self->{_sobrenome} ).", ".$self->{_nome}; 43 | } 44 | 45 | sub escreveNome 46 | { 47 | my ( $self ) = @_; 48 | return $self->{ _nome } 49 | } 50 | 51 | sub DESTROY 52 | { 53 | 54 | } 55 | 56 | our $AUTOLOAD; 57 | sub AUTOLOAD 58 | { 59 | die "Ei, o método $AUTOLOAD não existe!\n"; 60 | } 61 | 1; 62 | -------------------------------------------------------------------------------- /xml-em-perl-parte-3/ped.phtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Ped>histórico de exercícios 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |

Histórico de exercícios

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
Exercícios%_WORKOUTS_%
Maior distância%_FARTHEST_% km
Distância total%_RUNDISTANCE_% km
Tempo total%_TOTALHOU_%h %_TOTALMIN_%m %_TOTALSEC_%s
Calorias%_CALORIES_%
Número de passos%_TOTALSTEPS_%
  Caminhando%_WALKING_%
  Correndo%_RUNNING_%
  Passada˜%_MYSTEPS_% m
28 | Criado automaticamente pelo 'ped' 29 |
30 | 31 | 32 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/converting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from PIL import Image 3 | 4 | from functions import ( 5 | bsave, 6 | convert_palette, 7 | convert_to_vram, 8 | count_colors, 9 | quantize_colors, 10 | reduce_colors, 11 | split_pages, 12 | ) 13 | 14 | MAX_LINES = 256 15 | 16 | VALID_SIZES = ((256, 192), (256, 384), (512, 192), (512, 384)) 17 | 18 | image = Image.open("sample_512x384.png") 19 | 20 | try: 21 | # força o programa a aceitar imagens em 256×192 ou 512×384 22 | assert (image.width, image.height) in VALID_SIZES 23 | 24 | mode = "7" if image.width == 512 else "5" 25 | 26 | # recupera a lista de cores 27 | colors = count_colors(image) 28 | 29 | # converte a imagem para 16 cores sem aplicar dithering 30 | palette = quantize_colors(colors, 16) 31 | screen = reduce_colors(image, palette, dither=True) 32 | 33 | # divide a imagem em páginas de vídeo, caso necessário 34 | pages = split_pages(screen) if image.height > MAX_LINES else (screen, None) 35 | 36 | # converte para o leiaute da VRAM e salva a imagem 37 | for number, data in enumerate(pages): 38 | if data: 39 | bsave(f"SAMPLE.P{mode}{number}", convert_to_vram(data)) 40 | 41 | # salva a paleta de cores 42 | bsave(f"SAMPLE.P{mode}L", convert_palette(palette)) 43 | 44 | # exibe a imagem convertida, use ".save()" para salvar em arquivo... 45 | image.show() 46 | image.save("sample_512x424_default_palette.png") 47 | 48 | except AssertionError: 49 | print( 50 | "Resolução inválida, use imagens com ", 51 | ", ".join([f"{w}×{h}" for w, h in VALID_SIZES]), 52 | ) 53 | -------------------------------------------------------------------------------- /usando-arquivos-csv-em-python/write_csv_as_dict.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Escreve arquivo CSV a partir de um dicionário. 4 | """ 5 | from csv import DictReader, DictWriter 6 | from random import uniform 7 | 8 | # arquivo de entrada 9 | STUDENTS_FILE = "students.csv" 10 | # arquivo de saída 11 | CLASS_FILE = "classes.csv" 12 | 13 | # colunas a utilizar no arquivo de entrada 14 | KEYS_TO_KEEP = ( 15 | "id", 16 | "nome", 17 | ) 18 | 19 | # nomes da colunas a adicionar 20 | CLASSES = ( 21 | "biologia", 22 | "educação física", 23 | "filosofia", 24 | "física", 25 | "geografia", 26 | "história", 27 | "literatura", 28 | "língua estrangeira", 29 | "língua portuguesa", 30 | "matemática", 31 | "química", 32 | ) 33 | 34 | if __name__ == "__main__": 35 | 36 | # gera números aleatórios com duas casas decimais 37 | grade = lambda: round(uniform(0.0, 10.0), 2) 38 | 39 | with open(CLASS_FILE, "w") as f: 40 | # instancia o objeto DictWriter 41 | w = DictWriter(f, fieldnames=list(KEYS_TO_KEEP + CLASSES)) 42 | # grava o cabeçalho 43 | w.writeheader() 44 | # lê o arquivo de entrada... 45 | for student in DictReader(open(STUDENTS_FILE, "r")): 46 | # escreve uma linha da união de dois dicionários, o primeiro 47 | # contém apenas as colunas definidas do arquivo de entrada e 48 | # o segundo contém os valores das novas colunas 49 | w.writerow( 50 | { 51 | **{key: student[key] for key in KEYS_TO_KEEP}, 52 | **{class_name: grade() for class_name in CLASSES}, 53 | } 54 | ) 55 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/jquery.isonscreen.js: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2010 2 | * @author Laurence Wheway 3 | * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 4 | * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. 5 | * 6 | * @version 1.2.0 7 | */ 8 | (function($) { 9 | jQuery.extend({ 10 | isOnScreen: function(box, container) { 11 | //ensure numbers come in as intgers (not strings) and remove 'px' is it's there 12 | for(var i in box){box[i] = parseFloat(box[i])}; 13 | for(var i in container){container[i] = parseFloat(container[i])}; 14 | 15 | if(!container){ 16 | container = { 17 | left: $(window).scrollLeft(), 18 | top: $(window).scrollTop(), 19 | width: $(window).width(), 20 | height: $(window).height() 21 | } 22 | } 23 | 24 | if( box.left+box.width-container.left > 0 && 25 | box.left < container.width+container.left && 26 | box.top+box.height-container.top > 0 && 27 | box.top < container.height+container.top 28 | ) return true; 29 | return false; 30 | } 31 | }) 32 | 33 | 34 | jQuery.fn.isOnScreen = function (container) { 35 | for(var i in container){container[i] = parseFloat(container[i])}; 36 | 37 | if(!container){ 38 | container = { 39 | left: $(window).scrollLeft(), 40 | top: $(window).scrollTop(), 41 | width: $(window).width(), 42 | height: $(window).height() 43 | } 44 | } 45 | 46 | if( $(this).offset().left+$(this).width()-container.left > 0 && 47 | $(this).offset().left < container.width+container.left && 48 | $(this).offset().top+$(this).height()-container.top > 0 && 49 | $(this).offset().top < container.height+container.top 50 | ) return true; 51 | return false; 52 | } 53 | })(jQuery); 54 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-3/2_hierarquia_incorreta.txt: -------------------------------------------------------------------------------- 1 | 1:Sudeste 2 | 3:Rio de Janeiro 3 | 3:Angra dos Reis 4 | 3:Aperibé 5 | 3:Araruama 6 | 3:Areal 7 | 3:Armação dos Búzios 8 | 3:Arraial do Cabo 9 | 3:Barra Mansa 10 | 3:Barra do Piraí 11 | 3:Belford Roxo 12 | 3:Bom Jardim 13 | 3:Bom Jesus do Itabapoana 14 | 3:Cabo Frio 15 | 3:Cachoeiras de Macacu 16 | 3:Cambuci 17 | 3:Campos dos Goytacazes 18 | 3:Cantagalo 19 | 3:Carapebus 20 | 3:Cardoso Moreira 21 | 3:Carmo 22 | 3:Casimiro de Abreu 23 | 3:Comendador Levy Gasparian 24 | 3:Conceição de Macabu 25 | 3:Cordeiro 26 | 3:Duas Barras 27 | 3:Duque de Caxias 28 | 3:Engenheiro Paulo de Frontin 29 | 3:Guapimirim 30 | 3:Iguaba Grande 31 | 3:Itaboraí 32 | 3:Itaguaí 33 | 3:Italva 34 | 3:Itaocara 35 | 3:Itaperuna 36 | 3:Itatiaia 37 | 3:Japeri 38 | 3:Laje do Muriaé 39 | 3:Macuco 40 | 3:Magé 41 | 3:Mangaratiba 42 | 3:Maricá 43 | 3:Mendes 44 | 3:Mesquita 45 | 3:Miguel Pereira 46 | 3:Miracema 47 | 3:Natividade 48 | 3:Nilópolis 49 | 3:Niterói 50 | 3:Nova Friburgo 51 | 3:Nova Iguaçu 52 | 3:Paracambi 53 | 3:Paraty 54 | 3:Paraíba do Sul 55 | 3:Paty do Alferes 56 | 3:Petrópolis 57 | 3:Pinheiral 58 | 3:Piraí 59 | 3:Porciúncula 60 | 3:Porto Real 61 | 3:Quatis 62 | 3:Queimados 63 | 3:Quissamã 64 | 3:Resende 65 | 3:Rio Bonito 66 | 3:Rio Claro 67 | 3:Rio das Flores 68 | 3:Rio das Ostras 69 | 3:Rio de Janeiro 70 | 3:Santa Maria Madalena 71 | 3:Santo Antônio de Pádua 72 | 3:Sapucaia 73 | 3:Saquarema 74 | 3:Seropédica 75 | 3:Silva Jardim 76 | 3:Sumidouro 77 | 3:São Fidélis 78 | 3:São Francisco de Itabapoana 79 | 3:São Gonçalo 80 | 3:São José de Ubá 81 | 3:São José do Vale do Rio Preto 82 | 3:São João da Barra 83 | 3:São João de Meriti 84 | 3:São Pedro da Aldeia 85 | 3:São Sebastião do Alto 86 | 3:Tanguá 87 | 3:Teresópolis 88 | 3:Trajano de Moraes 89 | 3:Três Rios 90 | 3:Valença 91 | 3:Varre-Sai 92 | 3:Volta Redonda 93 | 94 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-3/1_nivel_hierarquico_invalido.txt: -------------------------------------------------------------------------------- 1 | 1:Sudeste 2 | 2:Rio de Janeiro 3 | 3:Angra dos Reis 4 | 4:Aperibé 5 | 5:Araruama 6 | 6:Areal 7 | 7:Armação dos Búzios 8 | 8:Arraial do Cabo 9 | 9:Barra Mansa 10 | 3:Barra do Piraí 11 | 3:Belford Roxo 12 | 3:Bom Jardim 13 | 3:Bom Jesus do Itabapoana 14 | 3:Cabo Frio 15 | 3:Cachoeiras de Macacu 16 | 3:Cambuci 17 | 3:Campos dos Goytacazes 18 | 3:Cantagalo 19 | 3:Carapebus 20 | 3:Cardoso Moreira 21 | 3:Carmo 22 | 3:Casimiro de Abreu 23 | 3:Comendador Levy Gasparian 24 | 3:Conceição de Macabu 25 | 3:Cordeiro 26 | 3:Duas Barras 27 | 3:Duque de Caxias 28 | 3:Engenheiro Paulo de Frontin 29 | 3:Guapimirim 30 | 3:Iguaba Grande 31 | 3:Itaboraí 32 | 3:Itaguaí 33 | 3:Italva 34 | 3:Itaocara 35 | 3:Itaperuna 36 | 3:Itatiaia 37 | 3:Japeri 38 | 3:Laje do Muriaé 39 | 3:Macuco 40 | 3:Magé 41 | 3:Mangaratiba 42 | 3:Maricá 43 | 3:Mendes 44 | 3:Mesquita 45 | 3:Miguel Pereira 46 | 3:Miracema 47 | 3:Natividade 48 | 3:Nilópolis 49 | 3:Niterói 50 | 3:Nova Friburgo 51 | 3:Nova Iguaçu 52 | 3:Paracambi 53 | 3:Paraty 54 | 3:Paraíba do Sul 55 | 3:Paty do Alferes 56 | 3:Petrópolis 57 | 3:Pinheiral 58 | 3:Piraí 59 | 3:Porciúncula 60 | 3:Porto Real 61 | 3:Quatis 62 | 3:Queimados 63 | 3:Quissamã 64 | 3:Resende 65 | 3:Rio Bonito 66 | 3:Rio Claro 67 | 3:Rio das Flores 68 | 3:Rio das Ostras 69 | 3:Rio de Janeiro 70 | 3:Santa Maria Madalena 71 | 3:Santo Antônio de Pádua 72 | 3:Sapucaia 73 | 3:Saquarema 74 | 3:Seropédica 75 | 3:Silva Jardim 76 | 3:Sumidouro 77 | 3:São Fidélis 78 | 3:São Francisco de Itabapoana 79 | 3:São Gonçalo 80 | 3:São José de Ubá 81 | 3:São José do Vale do Rio Preto 82 | 3:São João da Barra 83 | 3:São João de Meriti 84 | 3:São Pedro da Aldeia 85 | 3:São Sebastião do Alto 86 | 3:Tanguá 87 | 3:Teresópolis 88 | 3:Trajano de Moraes 89 | 3:Três Rios 90 | 3:Valença 91 | 3:Varre-Sai 92 | 3:Volta Redonda 93 | 94 | -------------------------------------------------------------------------------- /quantos-dias-tem-um-mes/numberofdays.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Number of Days 4 | # Print the number of days in a/this month 5 | # 6 | # Copyright 2015, Giovanni Nunes 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; either version 2 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | # MA 02110-1301, USA. 22 | # 23 | 24 | function numofdays() 25 | { 26 | MONTH=$1 27 | 28 | case $MONTH in 29 | # 30 | # feb 31 | # 32 | 2) 33 | cal -m 2 | grep 29 >/dev/null 2>&1 34 | if [ $? -eq 0 ] 35 | then 36 | DAYS=29 # leap year 37 | else 38 | DAYS=28 # ordinary year 39 | fi 40 | ;; 41 | # 42 | # apr, jun, sep and nov 43 | # 44 | 4|6|9|11) 45 | DAYS=30 46 | ;; 47 | # 48 | # jan, mar, may, jul, aug, oct and dec 49 | # 50 | 1|3|5|7|8|10|12) 51 | DAYS=31 52 | ;; 53 | # 54 | # oh my god! they created a new month! 55 | # 56 | *) 57 | DAYS=0 58 | ;; 59 | esac 60 | # 61 | # send the number of day 62 | # 63 | echo ${DAYS} 64 | } 65 | 66 | case $1 in 67 | 1|2|3|4|5|6|7|8|9|10|11|12) 68 | numofdays $1 69 | ;; 70 | '') 71 | numofdays $( date +%-m ) 72 | ;; 73 | *) 74 | echo "What?" 75 | exit 1 76 | ;; 77 | esac 78 | 79 | exit 0 80 | -------------------------------------------------------------------------------- /um-outro-exemplo-de-angularjs/exemplo-abj-2.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Exemplo AngularJS 2 1.0 3 | * 4 | * Outro exemplo de página web só com AngularJS 5 | * 6 | * Copyright 2015, Giovanni Nunes 7 | * 8 | * This program is free software; you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation; either version 2 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with this program; if not, write to the Free Software 20 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | * MA 02110-1301, USA. 22 | * 23 | */ 24 | (function(){ 25 | 26 | var app=angular.module('exemplo2', []) 27 | .controller("BoletimCtrl", [ '$http',function($http) { 28 | 29 | this.bimestres=[1,2,3,4]; 30 | this.agora=Date.now(); 31 | 32 | var exemplo2=this; 33 | exemplo2.turma=[]; 34 | 35 | /* 36 | * carrega a base de dados via HTTP 37 | */ 38 | this.file=$http.get('exemplo-abj-2.json').then(function(result) { 39 | if ( result.status==200){ 40 | exemplo2.turma=result.data; 41 | } else { 42 | alert("Erro ao carregar o arquivo JSON!"); 43 | } 44 | }); 45 | 46 | /* 47 | * calculo da média aritmética de um array de números 48 | */ 49 | this.mediaAritmetica=function(lista) { 50 | var itens=lista.length; 51 | var soma=0; 52 | for ( i=0; i str: 5 | """Calcula o dígito de verificação para ISBN-10.""" 6 | 7 | # a variável com o dígito de verificação 8 | digit = 0 9 | 10 | for i, j in zip((int(i) for i in isbn10), range(10, 1, -1)): 11 | # faz o primeiro dígito do ISBN×10, o segundo×9 etc 12 | digit += i * j 13 | 14 | # usa apenas o módulo 11 da soma 15 | digit %= 11 16 | 17 | # subtrai por 11, faz o módulo 11 e retorna o dígito como string... 18 | return str((11 - digit) % 11) 19 | 20 | 21 | def __calculate_isbn13_digit(isbn13: str) -> str: 22 | """Calcula o dígito de verificação para ISBN-13.""" 23 | 24 | # dígito de verificação a ser calculado 25 | digit = 0 26 | 27 | for i, j in enumerate((int(i) for i in isbn13), start=1): 28 | # se a posição do dígito é par, soma dígito×3 senão apenas dígito 29 | digit += j if i % 2 else j * 3 30 | 31 | # módulo 10 subtraído por 10 32 | digit = 10 - (digit % 10) 33 | 34 | # converte o dígito para string (quando for 10 retornará '0') 35 | return str(digit)[-1] 36 | 37 | 38 | def __calculate_isbn_digit(isbn: str) -> str: 39 | """Calcula o dígito de verificação para o ISBN.""" 40 | # se o ISBN informado não contiver números nem perco meu tempo 41 | 42 | if isbn.isdigit(): 43 | if len(isbn) == 9: 44 | # é ISBN-10 45 | return __calculate_isbn10_digit(isbn) 46 | elif len(isbn) == 12: 47 | # é ISBN-13 48 | return __calculate_isbn13_digit(isbn) 49 | 50 | raise ValueError("ISBN doesn't match as ISBN-10 or ISBN-13.") 51 | 52 | 53 | def validate_isbn_digit(isbn: str) -> bool: 54 | """Valida o dígito de verificação de um dado ISBN.""" 55 | 56 | digit = __calculate_isbn_digit(isbn[:-1]) 57 | 58 | return True if digit == isbn[-1] else False 59 | -------------------------------------------------------------------------------- /convertendo-imagens-para-o-atari-st/degas.py: -------------------------------------------------------------------------------- 1 | from divisiblelist import DivisibleList 2 | from PIL import Image 3 | 4 | 5 | def load_pic(filename): 6 | raw = open(filename, "rb").read() 7 | width, height, bpp = get_resolution(raw[0:2]) 8 | palette = get_palette(raw[2:34]) 9 | chunks = get_chunks(raw[34::]) 10 | 11 | image = Image.new("RGB", (width, height)) 12 | bitmap = image.load() 13 | 14 | words = DivisibleList(chunks) / {bpp} 15 | 16 | for y in range(height): 17 | for x in range(0, width, 16): 18 | pixels = dechunky(next(words)) 19 | for index, pixel in enumerate(pixels): 20 | bitmap[x + index, y] = palette[pixel] 21 | 22 | return image 23 | 24 | 25 | def get_resolution(res): 26 | return { 27 | 0: (320, 200, 4), 28 | 1: (640, 200, 2), 29 | 2: (640, 400, 1), 30 | }[int.from_bytes(res, byteorder="big")] 31 | 32 | 33 | def get_palette(pal): 34 | return [ 35 | ( 36 | (color[0] & 0x0F) << 5, 37 | (color[1] & 0xF0) << 1, 38 | (color[1] & 0x0F) << 5, 39 | ) 40 | for color in DivisibleList(pal) / 16 41 | ] 42 | 43 | 44 | def get_chunks(data): 45 | return [ 46 | int.from_bytes(word, byteorder="big") 47 | for word in DivisibleList(data) / {2} 48 | ] 49 | 50 | 51 | POWS_OF_TWO = ( 52 | (0, 32768), 53 | (1, 16384), 54 | (2, 8192), 55 | (3, 4096), 56 | (4, 2048), 57 | (5, 1024), 58 | (6, 512), 59 | (7, 256), 60 | (8, 128), 61 | (9, 64), 62 | (10, 32), 63 | (11, 16), 64 | (12, 8), 65 | (13, 4), 66 | (14, 2), 67 | (15, 1), 68 | ) 69 | 70 | 71 | def dechunky(words): 72 | pixels = [0 for __ in range(16)] 73 | for col, bit in POWS_OF_TWO: 74 | for word in words[::-1]: 75 | pixels[col] <<= 1 76 | pixels[col] |= 1 if word & bit else 0 77 | 78 | return pixels 79 | -------------------------------------------------------------------------------- /usando-grupos-em-expressoes-regulares/lorem_ipsum.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris hendrerit ligula neque, vitae tempus nulla scelerisque et. Nunc feugiat pellentesque dictum. Vivamus dignissim nisl eget suscipit tempus. In hac habitasse platea dictumst. Quisque id gravida velit. Quisque sed dictum leo. Sed aliquet sodales interdum. In justo tellus, imperdiet ut dignissim a, varius in sapien. Integer malesuada vestibulum leo, vel eleifend ex rhoncus sit amet. Mauris egestas rhoncus porttitor. Curabitur sed dolor ac tortor blandit mollis quis vel massa. 2 | Ut sit amet faucibus neque. Vivamus maximus sodales ex sed imperdiet. Aliquam sed dignissim nisl, id semper felis. In ac lacus quis velit mattis interdum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean pulvinar egestas mauris non facilisis. Quisque efficitur diam placerat, iaculis turpis a, semper felis. Maecenas a dolor eget ex volutpat pretium. Suspendisse aliquet turpis quis auctor congue. Donec tempus volutpat lorem. Praesent accumsan nec magna eget iaculis. Vestibulum commodo accumsan odio ut tincidunt. Phasellus ut tortor laoreet, facilisis turpis luctus, pulvinar nisi. Etiam aliquam lorem et justo pretium posuere. 3 | Sed malesuada, arcu id semper lacinia, odio leo ultrices magna, vitae condimentum nibh urna eget ligula. Aenean sed maximus augue, sed volutpat orci. Aliquam erat volutpat. Praesent consectetur eleifend tincidunt. Etiam non mauris feugiat, ullamcorper neque id, auctor dolor. Etiam in ex nunc. Praesent euismod eros a nibh volutpat elementum. Vestibulum volutpat eget ex sed interdum. Nam congue enim mauris, ut placerat sapien fringilla vehicula. Fusce dictum odio sodales consequat pellentesque. Proin commodo velit placerat hendrerit feugiat. Nam egestas venenatis mi, non efficitur sapien. Nam feugiat mauris arcu, nec efficitur sapien rhoncus eu. 4 | Nulla aliquam ut tellus ac lobortis. Morbi lacus orci, placerat ac porttitor et, egestas nec turpis. Suspendisse elit magna, feugiat id feugiat ac, tristique vel magna. Sed rutrum neque at erat. 5 | -------------------------------------------------------------------------------- /faxina-no-boot/oldkernelcleaner.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Old Kernel Cleaner (Ubuntu) 4 | # Just a way to remove older linux kernel images from a Ubuntu system 5 | # 6 | # Copyright 2015, Giovanni Nunes 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; either version 2 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | # MA 02110-1301, USA. 22 | # 23 | 24 | # keeping at least 25 | TOKEEP=3 26 | 27 | # remove counter 28 | TOREMO=0 29 | 30 | # get LSB release information 31 | source /etc/lsb-release 32 | 33 | # check where is running. 34 | if [ ${DISTRIB_ID} = "Ubuntu" ]; then 35 | PACKAGE='linux-image' 36 | LINUX=$( dpkg -l ${PACKAGE}-[0-9]* | grep "ii " | awk '{ print $2 }' | tac ) 37 | COUNT=0 38 | LIST='' 39 | # for each package found... 40 | for IMAGE in ${LINUX}; do 41 | if [ ${COUNT} -lt ${TOKEEP} ] ; then 42 | if [ ${COUNT} -eq 0 ]; then 43 | echo "Keeping:" 44 | fi 45 | echo " ${IMAGE}" 46 | else 47 | LIST=${LIST}' '${IMAGE} 48 | TOREMO=$((TOREMO=+1)) 49 | fi 50 | COUNT=$((COUNT+1)) 51 | done 52 | if [ ${TOREMO} -gt 0 ]; then 53 | # for safety I don't run 'apt-get', please copy & paste 54 | echo -e "\nTry this:\napt-get remove --purge${LIST}" 55 | else 56 | echo -e "\nNothing to do!" 57 | fi 58 | else 59 | echo "Ubuntu only!" 60 | exit 1 61 | fi 62 | 63 | exit 0 64 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/module/colors.py: -------------------------------------------------------------------------------- 1 | """ 2 | Classe para gerenciar paletas de cores 3 | """ 4 | from typing import List, Tuple 5 | 6 | ColorType = Tuple[int, ...] 7 | ColorTupleType = Tuple[ColorType, ...] 8 | PaletteType = List[str] 9 | 10 | 11 | class BaseColors: 12 | """ 13 | Classe base para criação de paletas de cores 14 | """ 15 | 16 | def create_palette(self, name: str, values: PaletteType) -> None: 17 | """ 18 | Define atributos na classe para a criação da paleta de cores. 19 | """ 20 | 21 | def hex_to_tuple(hex_color: str) -> ColorType: 22 | """ 23 | Converte um número hexadecimal em _string_ (0xRRGGBB) em uma 24 | tupla com números inteiros (R, G, B). 25 | """ 26 | color = hex_color.rjust(6, "0") 27 | 28 | return tuple(int(color[i : i + 2], 16) for i in range(0, 6, 2)) 29 | 30 | color_tuple: ColorTupleType = tuple( 31 | [hex_to_tuple(color) for color in values] 32 | ) 33 | 34 | setattr(self, name, color_tuple) 35 | 36 | 37 | class TangoColors(BaseColors): 38 | """ 39 | Define uma paleta de cores baseado nas cores do projeto Tango Desktop 40 | """ 41 | 42 | PALETTE = { 43 | "butter": ["fce94f", "edd400", "c4a000",], 44 | "orange": ["fcaf3e", "f57900", "ce5c00",], 45 | "chocolate": ["e9b96e", "c17d11", "8f5902",], 46 | "chameleon": ["8ae234", "73d216", "4e9a06",], 47 | "sky": ["729fcf", "3465a4", "204a87",], 48 | "plum": ["ad7fa8", "75507b", "5c3566",], 49 | "scarlet": ["ef2929", "cc0000", "a40000"], 50 | "aluminium": [ 51 | "ffffff", 52 | "eeeeec", 53 | "d3d7cf", 54 | "babdb6", 55 | "888a85", 56 | "555753", 57 | "2e3436", 58 | "000000", 59 | ], 60 | } 61 | 62 | def __init__(self) -> None: 63 | """ 64 | Inicializa a classe carregando a paleta definida em PALETTE 65 | """ 66 | for color, values in self.PALETTE.items(): 67 | self.create_palette(color, values) 68 | -------------------------------------------------------------------------------- /maquina-virtual-em-perl/mymac.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # MyMAC.pl 4 | # My implementantion in PERL od Felix Angel's simple virtual 5 | # machine -- https://github.com/felixangell/mac 6 | # 7 | # Copyright 2015, Giovanni Nunes 8 | # 9 | # This program is free software; you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation; either version 2 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program; if not, write to the Free Software 21 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 22 | # MA 02110-1301, USA. 23 | # 24 | use strict; 25 | 26 | use constant PSH => 0; 27 | use constant ADD => 1; 28 | use constant POP => 2; 29 | use constant HLT => 3; 30 | 31 | use constant True => 1; 32 | use constant False => 0; 33 | 34 | my $ip=0; 35 | my $sp=-1; 36 | my $running=True; 37 | 38 | my @stack=(undef); 39 | 40 | my @program=( PSH, 5, 41 | PSH, 6, 42 | ADD, 43 | POP, 44 | HLT ); 45 | 46 | sub fetch() 47 | { 48 | return $program[$ip]; 49 | } 50 | 51 | sub eval() 52 | { 53 | my $instr=$_[0]; 54 | 55 | if ( $instr == HLT ) 56 | { 57 | $running=False; 58 | print "done\n"; 59 | } 60 | elsif ( $instr == PSH ) 61 | { 62 | $sp++; 63 | $stack[$sp]=$program[++$ip]; 64 | print "push\n"; 65 | } 66 | elsif ( $instr == POP ) 67 | { 68 | my $val_popped = $stack[$sp--]; 69 | print "popped $val_popped\n"; 70 | } 71 | elsif ( $instr == ADD ) 72 | { 73 | my $a = $stack[$sp--]; 74 | my $b = $stack[$sp--]; 75 | 76 | my $result=$b+$a; 77 | 78 | $sp++; 79 | $stack[$sp]=$result; 80 | print "add\n"; 81 | } 82 | } 83 | 84 | while( $running == True) 85 | { 86 | &eval( &fetch() ); 87 | $ip++; 88 | } 89 | 90 | exit 0 91 | -------------------------------------------------------------------------------- /decoradores-em-python/testa_decoradores.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Testa os decoradores 5 | """ 6 | from __future__ import print_function 7 | from json import loads as json_loads 8 | 9 | # from decoradores import html # descomente para saída em HTML 10 | # from decoradores import markdown # descomente para saída em Markdown 11 | 12 | 13 | DEFAULT_VALUE = "" 14 | NOTAS_JSON = "notas.json" 15 | 16 | # @markdown # descomente para saída em Markdown 17 | # @html # descomente para saída em HTML 18 | def tabulate_data(data_dict, sort_keys=True, sort_data=False): 19 | """ Converte um dicionário em uma lista em forma de tabela com as 20 | chaves do dicionário formando a primeira linha (cebeçalho) e os dados 21 | logo em sequência. Recebe o dicionárip em `data_dict` e opcionalmente 22 | os parâmetros `sort_keys` e `sort_data` como bolianos para respectivamente 23 | ordenar, ou não, as chaves do dicionário e seus dados. """ 24 | 25 | # variáveis 26 | table_values = [] 27 | temp_header_set = set() 28 | 29 | # itera em todas as chaves do dicionário e alimenta um 'set'. 30 | for i in data_dict: 31 | __ = [temp_header_set.add(j) for j in i.keys()] 32 | 33 | # converte o 'set' em uma lista, ordenando a ordem das chaves se o 34 | # conteúdo da variável `sort_keys` for `True`. 35 | table_header = list(sorted(temp_header_set) if sort_keys else temp_header_set) 36 | 37 | # para cada componente do cabeçalho, recupera seu valor, ou então 38 | # usa o valor padrão. 39 | for j in data_dict: 40 | table_values.append([j.get(keys, DEFAULT_VALUE) for keys in table_header]) 41 | 42 | # ordena os dados se o valor da variável `sort_data` for `True`. 43 | if sort_data: 44 | table_values.sort() 45 | 46 | return [table_header] + table_values 47 | 48 | 49 | def main(): 50 | """ Função principal. """ 51 | 52 | # lê o arquivo JSON com as notas (melhor que colocá-lo aqui no código) 53 | notas_json = json_loads(open(NOTAS_JSON, "r").read()) 54 | 55 | # tabula os dados lidos do JSON... 56 | dados_alunos = tabulate_data(notas_json) 57 | 58 | # imprime na tela (ou salva em disco se for o caso) 59 | print(dados_alunos) 60 | 61 | 62 | if __name__ == "__main__": 63 | main() 64 | -------------------------------------------------------------------------------- /mais-decoradores-em-python/module/decorators.py: -------------------------------------------------------------------------------- 1 | """ 2 | Decoradores usados como exemplo. 3 | """ 4 | from typing import Callable 5 | 6 | 7 | def marker(func_obj) -> Callable: 8 | """ 9 | (decorador) Realça uma _string_ usando outras cores. 10 | """ 11 | 12 | def decorator(*args: str, **kvargs: int) -> str: 13 | """ 14 | Adiciona os códigos VT-100 necessários para mudar a cor de uma 15 | string na tela. 16 | """ 17 | fore, back = (0, 15, 0,), (0, 255, 63,) 18 | 19 | return ( 20 | "\x1b[38;2;{};{};{}m".format(*fore) 21 | + "\x1b[48;2;{};{};{}m".format(*back) 22 | + func_obj(*args, **kvargs) 23 | + "\x1b[0m" 24 | ) 25 | 26 | return decorator 27 | 28 | 29 | def marker2(fore: tuple, back: tuple) -> Callable: 30 | """ 31 | (decorador) Realça uma _string_ usando cores de frente como `fore` 32 | e de fundo como `back`. 33 | """ 34 | 35 | def wrapper(func_obj) -> Callable: 36 | """ 37 | Envelopa a função a ser chamada. 38 | """ 39 | 40 | def decorator(*args: str, **kvargs: int) -> str: 41 | """ 42 | Adiciona os códigos VT-100 necessários para mudar a cor de uma 43 | string na tela. 44 | """ 45 | return ( 46 | "\x1b[38;2;{};{};{}m".format(*fore) 47 | + "\x1b[48;2;{};{};{}m".format(*back) 48 | + func_obj(*args, **kvargs) 49 | + "\x1b[0m" 50 | ) 51 | 52 | return decorator 53 | 54 | if len(fore) != 3 or len(back) != 3: 55 | raise ValueError("Cores precisam ser tuplas com valores de (R, G, B)!") 56 | 57 | return wrapper 58 | 59 | 60 | def multiply(factor: float) -> Callable: 61 | """ 62 | Multiplica qualquer valor recebido pelo valor de `factor`. 63 | """ 64 | 65 | def wrapper(func_obj) -> Callable: 66 | """ 67 | Envelopa o decorador... 68 | """ 69 | 70 | def decorator(*args: str, **kvargs: int) -> float: 71 | """ 72 | Executa a função decorada pelo valor informado. 73 | """ 74 | return func_obj(*args, **kvargs) * factor 75 | 76 | return decorator 77 | 78 | return wrapper 79 | -------------------------------------------------------------------------------- /convertendo-imagens-para-msx/functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Funções para a conversão de imagens em PNG para o modo de vídeo de 3 | 256 coresw dos MSX2. 4 | """ 5 | FLOYD_STEINBERG_NEIGHBORS = ( 6 | (+1, 0, 7), 7 | (-1, +1, 3), 8 | (-1, +1, 5), 9 | (+1, +1, 1), 10 | ) 11 | 12 | 13 | def add_noise(bitmap, x, y, error): 14 | """ 15 | Adiciona ruído nos pixeis vizinhos aplicando a diferença nos 16 | valores RGB da cor original e seu valor após a reducção. 17 | """ 18 | for offset_x, offset_y, debt in FLOYD_STEINBERG_NEIGHBORS: 19 | try: 20 | off_x, off_y = x + offset_x, y + offset_y 21 | bitmap[off_x, off_y] = tuple( 22 | ( 23 | color + error * debt // 16 24 | for color, error in zip(bitmap[off_x, off_y], error) 25 | ) 26 | ) 27 | except IndexError: 28 | ... 29 | 30 | 31 | def bsave(filename, vram): 32 | """ 33 | Monta o cabeçalho e salva um arquivo no formato binário do MSX-BASIC. 34 | """ 35 | vram_size = len(vram) - 1 36 | 37 | assert isinstance(vram, bytearray) and vram_size < 65535 38 | 39 | header = bytearray( 40 | (0xFE, 0x00, 0x00, vram_size % 256, vram_size // 256, 0x00, 0x00,) 41 | ) 42 | 43 | with open(filename, "wb") as f: 44 | f.write(header) 45 | f.write(vram) 46 | 47 | 48 | def reduce_color(r, g, b, *args): 49 | """ 50 | Reduz a resolução das cores. Basicamente deveria fazer a divisão 51 | inteira por 32 (R e G) ou 64 (B) mas para manter os valores 52 | compatíveis pelo Pillow este teriam de ser novamente multiplicados 53 | e daí fica mais simplles fazer uma operação lógica AND deixando 54 | só os bits necessários. 55 | """ 56 | r &= 0xE0 57 | g &= 0xE0 58 | b &= 0xC0 59 | 60 | return r, g, b 61 | 62 | 63 | def split_pages(vram, width=256): 64 | """ 65 | Divide as linhas pares e ímpares da imagem em páginas distintas. 66 | """ 67 | page_0, page_1 = bytearray(), bytearray() 68 | vram_size = len(vram) - 1 69 | block = width * 2 70 | 71 | line = 0 72 | 73 | while line < vram_size: 74 | page_0 += vram[line : line + width] 75 | page_1 += vram[line + width : line + block] 76 | line += block 77 | 78 | return page_0, page_1 79 | 80 | 81 | def to_msx2_rgb(r, g, b): 82 | """ 83 | Monta o pixel do modo de 256 cores. 84 | """ 85 | return g | r >> 3 | b >> 6 86 | -------------------------------------------------------------------------------- /usando-grupos-em-expressoes-regulares/lorem_ipsum.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | LOREM IPSUM 4 | 5 | 20 | 21 |
22 |

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris hendrerit ligula neque, vitæ tempus nulla scelerisque et. Nunc feugiat pellentesque dictum. Vivamus dignissim nisl eget suscipit tempus. In hac habitasse platea dictumst. Quisque id gravida velit. Quisque sed dictum leo. Sed aliquet sodales interdum. In justo tellus, imperdiet ut dignissim a, varius in sapien. Integer malesuada vestibulum leo, vel eleifend ex rhoncus sit amet. Mauris egestas rhoncus porttitor. Curabitur sed dolor ac tortor blandit mollis quis vel massa.

23 |

Ut sit amet faucibus neque. Vivamus maximus sodales ex sed imperdiet. Aliquam sed dignissim nisl, id semper felis. In ac lacus quis velit mattis interdum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curæ; Aenean pulvinar egestas mauris non facilisis. Quisque efficitur diam placerat, iaculis turpis a, semper felis. Mæcenas a dolor eget ex volutpat pretium. Suspendisse aliquet turpis quis auctor congue. Donec tempus volutpat lorem. Præsent accumsan nec magna eget iaculis. Vestibulum commodo accumsan odio ut tincidunt. Phasellus ut tortor laoreet, facilisis turpis luctus, pulvinar nisi. Etiam aliquam lorem et justo pretium posuere.

24 |

Sed malesuada, arcu id semper lacinia, odio leo ultrices magna, vitæ condimentum nibh urna eget ligula. Aenean sed maximus augue, sed volutpat orci. Aliquam erat volutpat. Præsent consectetur eleifend tincidunt. Etiam non mauris feugiat, ullamcorper neque id, auctor dolor. Etiam in ex nunc. Præsent euismod eros a nibh volutpat elementum. Vestibulum volutpat eget ex sed interdum. Nam congue enim mauris, ut placerat sapien fringilla vehicula. Fusce dictum odio sodales consequat pellentesque. Proin commodo velit placerat hendrerit feugiat. Nam egestas venenatis mi, non efficitur sapien. Nam feugiat mauris arcu, nec efficitur sapien rhoncus eu.

25 |

Nulla aliquam ut tellus ac lobortis. Morbi lacus orci, placerat ac porttitor et, egestas nec turpis. Suspendisse elit magna, feugiat id feugiat ac, tristique vel magna. Sed rutrum neque at erat.

26 |
27 | 28 | 29 | -------------------------------------------------------------------------------- /registro-de-eventos-em-python/hal_quotes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ hal_quotes.py : Exemplo de uso do módulo 'logging' dentro de uma função. 3 | """ 4 | # -*- coding: utf-8 -*- 5 | from __future__ import print_function 6 | from os import environ 7 | import logging 8 | 9 | 10 | # Use COLS para alterar a largura do terminal 11 | COLUMNS = int(environ.get('COLS', 80)) - 1 12 | 13 | # As citações do HAL9000, extraídas de: 14 | # https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film) 15 | QUOTES = { 16 | 'DEBUG': 'Affirmative, Dave. I read you.', 17 | 'INFO': 'This mission is too important for me to allow you to jeopardize it.', 18 | 'WARNING': 'Without your space helmet, Dave, you\'re going to find that rather difficult.', 19 | 'ERROR': 'I\'m sorry, Dave. I\'m afraid I can\'t do that.', 20 | 'CRITICAL': 'Dave, this conversation can serve no purpose any more. Goodbye' 21 | } 22 | 23 | # Recupera as chaves de `QUOTES` (É preguiça que chama) 24 | LEVELS = QUOTES.keys() 25 | 26 | # As cores utilizadas 27 | COLORS = { 28 | 'NONE': (79, 79, 127), 29 | 'DEBUG': (0, 191, 255), 30 | 'INFO': (0, 192, 0), 31 | 'WARNING': (255, 255, 0), 32 | 'ERROR': (255, 127, 0), 33 | 'CRITICAL': (255, 31, 0), 34 | } 35 | 36 | 37 | def colored(text, color='NONE'): 38 | """ Muda as cores do texto. Só funcionará em terminais com suporte 39 | a este recurso. """ 40 | red, green, blue = COLORS.get(color) 41 | return "\x1b[38;2;{r};{g};{b}m{msg}\x1b[0m".format( 42 | r=red, g=green, b=blue, msg=text) 43 | 44 | 45 | def hal9000_quotes(new_level): 46 | """ Escreve as citações do HAL na STDERR. """ 47 | # recupera o logger do programa 48 | hal_log = logging.getLogger(__name__) 49 | 50 | # define o novo nível de log 51 | hal_log.setLevel(new_level) 52 | 53 | # exibe as mensagens 54 | hal_log.debug(colored(QUOTES['DEBUG'], 'DEBUG')) 55 | hal_log.info(colored(QUOTES['INFO'], 'INFO')) 56 | hal_log.warning(colored(QUOTES['WARNING'], 'WARNING')) 57 | 58 | # quando em 'DEBUG', repita a mensagem 4 vezes... 59 | times = 4 if new_level == 'DEBUG' else 1 60 | for __ in range(0, times): 61 | hal_log.error(colored(QUOTES['ERROR'], 'ERROR')) 62 | 63 | hal_log.critical(colored(QUOTES['CRITICAL'], 'CRITICAL')) 64 | 65 | 66 | def main(): 67 | """ Função principal. """ 68 | 69 | # inicializa o módulo logging 70 | logging.basicConfig(level=logging.DEBUG, 71 | format='2001-Sep-28 - %(levelname)s - %(message)s') 72 | 73 | # brinca de publicar mensagens 74 | for level in reversed(list(LEVELS)): 75 | hal9000_quotes(level) 76 | logging.shutdown() 77 | print(colored('-' * COLUMNS)) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /gerador-de-arquivos-ips/IPSmaker.pm: -------------------------------------------------------------------------------- 1 | # 2 | # IPSmaker v0.1 (Perl Module) 3 | # 4 | # This file contais the class used in IPSmaker 5 | # 6 | # Copyright 2015, Giovanni Nunes 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; either version 2 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software 20 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 21 | # MA 02110-1301, USA. 22 | # 23 | package IPSmaker; 24 | use strict; 25 | use warnings; 26 | 27 | sub new 28 | { 29 | my ( $class ) = shift; 30 | my $self={ FileName =>shift, FileSize=>0, FileData=>'' }; 31 | my ( $filesize, $filedata, $filename, $fh ); 32 | 33 | $filename = $self->{FileName}; 34 | 35 | open($fh, '<', $filename) or die "*** Could not open file '".$filename."'!"; 36 | 37 | binmode $fh,":raw"; 38 | $filesize=-s $filename; 39 | read $fh,$filedata,$filesize; 40 | 41 | close($fh); 42 | 43 | $self->{FileSize}=$filesize; 44 | $self->{FileData}=$filedata; 45 | 46 | bless $self, $class; 47 | return $self; 48 | } 49 | 50 | sub Byte() 51 | { 52 | my ( $self, $Pos ) = @_; 53 | 54 | if ( $Pos < $self->{FileSize} ) 55 | { 56 | return vec($self->{FileData}, $Pos, 8); 57 | } 58 | else 59 | { 60 | return -1; 61 | } 62 | } 63 | 64 | sub Record() 65 | { 66 | my ( $self, $Address, $Size ) = @_; 67 | return Spliter(sprintf('%06x',$Address)).Spliter(sprintf('%04x',$Size)).substr($self->{FileData}, $Address, $Size); 68 | } 69 | 70 | sub HexDump() 71 | { 72 | my ( $self, $IniPos, $EndPos ) = @_; 73 | 74 | my ( $Data, $Hex, $Ascii ); 75 | 76 | for ( my $Count=$IniPos; $Count<$EndPos; $Count++ ) 77 | { 78 | $Data=vec($self->{FileData}, $Count, 8); 79 | 80 | $Hex.=sprintf('%02x',$Data )." "; 81 | 82 | if ( $Data>=33 and $Data<=127 ) 83 | { 84 | $Ascii.=chr($Data); 85 | } 86 | else 87 | { 88 | $Ascii.='.'; 89 | } 90 | } 91 | 92 | return $Hex."\t".$Ascii; 93 | } 94 | 95 | sub Spliter() 96 | { 97 | my ( $i, $j, $Data, $Value ); 98 | 99 | $Value=$_[0]; 100 | 101 | for ( $i=0; $i 6 | # 7 | # This program is free software; you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation; either version 2 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with this program; if not, write to the Free Software 19 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 20 | # MA 02110-1301, USA. 21 | # 22 | use strict; 23 | use warnings; 24 | use IPSmaker; 25 | 26 | unless ( scalar @ARGV==0 ) 27 | { 28 | if ( -f $ARGV[0] ) 29 | { 30 | my $Original = IPSmaker->new( $ARGV[0] ); 31 | 32 | if ( -f $ARGV[1] ) 33 | { 34 | my $Modified = IPSmaker->new( $ARGV[1] ); 35 | 36 | if ( $Original->{FileSize} == $Modified->{FileSize} ) 37 | { 38 | my $Position=0; 39 | my $Mode=0; 40 | my $Start=0; 41 | my $Stop=0; 42 | 43 | my $IPSpatch = $ARGV[2]; 44 | 45 | open(my $FH, '>', $IPSpatch) or 46 | die "*** Could not create file '$IPSpatch' $!"; 47 | 48 | binmode $FH,":raw"; 49 | 50 | print $FH IPSmaker->Header(); 51 | 52 | do 53 | { 54 | if ( $Original->Byte($Position) != $Modified->Byte($Position) ) 55 | { 56 | if ( $Mode==0 ) 57 | { 58 | $Start=$Position; 59 | } 60 | $Mode=1; 61 | } 62 | else 63 | { 64 | if ( $Mode==1 ) 65 | { 66 | $Stop=$Position; 67 | print $FH $Modified->Record( $Start,($Stop-$Start) ); 68 | print sprintf('%06x',$Start)."\t".($Stop-$Start)."\t".$Modified->HexDump( $Start, $Stop )."\n"; 69 | } 70 | $Mode=0; 71 | } 72 | $Position++; 73 | } 74 | while( $Position<$Original->{FileSize} ); 75 | 76 | print $FH IPSmaker->Footer(); 77 | 78 | close($FH); 79 | } 80 | else 81 | { 82 | print "*** Files don't have the same size! Can't continue!\n"; 83 | exit 1 84 | } 85 | } 86 | else 87 | { 88 | print "*** $ARGV[1] not found!\n"; 89 | exit 1 90 | } 91 | } 92 | else 93 | { 94 | print "*** $ARGV[0] not found!\n"; 95 | exit 1 96 | } 97 | } 98 | else 99 | { 100 | print "IPSmaker (a simple IPS generator) v1.0\nCopyright (C) 2015 Giovanni Nunes\n\n". 101 | "This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions.\n\n". 102 | "Use: ipsmaker .ips\n"; 103 | } 104 | 105 | exit 0; 106 | 107 | # MSX Rulez 108 | -------------------------------------------------------------------------------- /usando-o-pydantic/books/models.py: -------------------------------------------------------------------------------- 1 | """Modelos de exemplo do Pydantic""" 2 | from datetime import datetime 3 | from enum import Enum 4 | from typing import Tuple 5 | from uuid import UUID, uuid4 6 | 7 | from pydantic import BaseModel, Field, validator 8 | 9 | from .validators import validate_isbn_digit 10 | 11 | 12 | class BookBase(BaseModel): 13 | """Classe básica com os dados de livro.""" 14 | 15 | id: int 16 | title: str 17 | subtitle: str = "" 18 | author: str 19 | 20 | 21 | class BookWithValidation(BookBase): 22 | """Classe de livro que valida autor e título.""" 23 | 24 | @validator("title", "author") 25 | def validate_not_empty(cls, value: str, **kwargs) -> str: 26 | """Verifica se os campos informados não estão vazios.""" 27 | if value == "": 28 | raise ValueError("value can't be an empty string") 29 | return value 30 | 31 | 32 | class BookWithISBN(BookWithValidation): 33 | """Classe de livro que valida autor, título e e ISBN.""" 34 | 35 | isbn: str 36 | 37 | @validator("isbn") 38 | def validate_isbn(cls, value: str, **kwargs) -> str: 39 | """Verifica se o ISBN informado é válido.""" 40 | if not validate_isbn_digit(value): 41 | raise ValueError("value is not a valid ISBN") 42 | return value 43 | 44 | 45 | class LanguageEnum(str, Enum): 46 | """Idiomas válidos para os livros.""" 47 | 48 | en = "English" 49 | pt = "Portuguese" 50 | 51 | 52 | class BookWithLanguage(BookWithISBN): 53 | """Classe de livro com validação e enumeração.""" 54 | 55 | language: LanguageEnum = LanguageEnum.pt 56 | 57 | 58 | class Shelf(BaseModel): 59 | """Class prateleira para guardar os livros.""" 60 | 61 | id: UUID 62 | books: Tuple[BookWithLanguage, ...] 63 | 64 | 65 | class BookV2(BaseModel): 66 | """Segunda versão da classe de livros contento todos os campos dos 67 | exemplos anteriores e mais alguns novos.""" 68 | 69 | id: int 70 | title: str 71 | subtitle: str = "" 72 | author: str 73 | publisher: str 74 | pages: int 75 | isbn: str 76 | language: LanguageEnum = LanguageEnum.pt 77 | 78 | @validator("title", "author", "publisher") 79 | def validate_not_empty(cls, value: str, **kwargs) -> str: 80 | """Verifica se os campos informados não estão vazios.""" 81 | if value == "": 82 | raise ValueError("value can't be an empty string") 83 | return value 84 | 85 | @validator("isbn") 86 | def validate_isbn(cls, value: str, **kwargs) -> str: 87 | """Verifica se o ISBN informado é válido.""" 88 | if not validate_isbn_digit(value): 89 | raise ValueError("value is not a valid ISBN") 90 | return value 91 | 92 | @validator("pages") 93 | def validate_not_zero(cls, value: int, **kwargs) -> int: 94 | """Verifica se o número de páginas é maior que 1.""" 95 | if value < 1: 96 | raise ValueError("number of pages can't be 0 or less") 97 | return value 98 | 99 | 100 | class ShelfV2(BaseModel): 101 | """Class prateleira para guardar os livros.""" 102 | 103 | id: UUID 104 | books: Tuple[BookV2, ...] 105 | created_at: datetime = datetime.now() 106 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Coverage report 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 19 | 20 | 21 | 22 | 35 | 36 |
37 | Hide keyboard shortcuts 38 |

Hot-keys on this page

39 |
40 |

41 | n 42 | s 43 | m 44 | x 45 | 46 | c   change column sorting 47 |

48 |
49 |
50 | 51 |
52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 |
Modulestatementsmissingexcludedcoverage
Total1302100%
pode_beber.py1302100%
88 | 89 |

90 | No items found using the specified filter. 91 |

92 |
93 | 94 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /exemplo-com-angularjs-bootstrap-e-jquery/exemplo-abj.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | {{ titulo.texto }} 13 | 14 | 15 | 19 |
20 | 23 |
24 |

{{ menu.texto }}

25 | 35 |
36 | 37 |
38 |

{{ jumbo.conteudo.texto }}

39 |

{{ jumbo.conteudo.descr }}

40 |

{{ jumbo.conteudo.botao }}

41 |
42 | 45 | 46 |
47 | 48 |
49 | 50 |

{{ conteudo.titulo }}

51 |

{{ conteudo.texto }}

52 |

Mais »

53 |
54 |
55 | 56 |
57 |
58 |
59 |

{{ sobre.conteudo.titulo }}

60 |

{{ sobre.conteudo.texto }}

61 |
{{ sobre.license }}
62 |

63 |
64 |
65 |
66 | 70 |
71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-3/municipios.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Exceções em Python - parte 3""" 3 | # -*- coding: utf-8 -*- 4 | from sys import argv 5 | 6 | 7 | class ParseError(Exception): 8 | """A exceção customizada utilizada pelo 'parser'.""" 9 | 10 | def __init__(self, mensagem, linha=0): 11 | """Construtor da classe, recebe o texto do erro (mensagem) e 12 | também o número da linha onde ocorreu (opcional).""" 13 | self.mensagem = mensagem 14 | self.linha = linha 15 | 16 | def __str__(self): 17 | """Imprime a mensagem de erro.""" 18 | return "Erro: {}".format(self.mensagem) + \ 19 | (" na linha {}!".format(self.linha) if self.linha > 0 else "!") 20 | 21 | 22 | class Municipios(object): 23 | """Classe que armazena os municípios por região e estado.""" 24 | # esta classe só aceita três níveis hierárquicos 25 | REGIAO = 1 26 | ESTADO = 2 27 | CIDADE = 3 28 | 29 | def __init__(self, municipios): 30 | """Construtor da classe, recebe o nome do arquivo a ser lido.""" 31 | try: 32 | with open(municipios, "r") as arquivo: 33 | self.__municipios = self.__parser(arquivo) 34 | except FileNotFoundError: 35 | raise ParseError("Arquivo não encontrado") from FileNotFoundError 36 | 37 | @property 38 | def regioes(self): 39 | """Propriedade `regioes`, retorna as regiões existentes.""" 40 | return [i for i in self.__municipios.keys()] 41 | 42 | def estados(self, regiao): 43 | """Retorna os estados de uma região específica.""" 44 | return [i for i in self.__municipios[regiao].keys()] 45 | 46 | def municipios(self, regiao, estado): 47 | """Retorna os municípios de um determinado estado.""" 48 | return self.__municipios[regiao][estado] 49 | 50 | def __parser(self, arquivo): 51 | """Interpreta o arquivo texto e retorna os dados em um dicionário 52 | ou chamará a exceção `ParseError` caso ocorra algo de errado.""" 53 | corrente = linha = 0 54 | municipios = {} 55 | 56 | for itens in arquivo: 57 | linha += 1 58 | if itens is not "\n": 59 | nivel, valor = itens.strip().split(":") 60 | nivel = int(nivel) 61 | if nivel <= (corrente + 1): 62 | if nivel == self.REGIAO: 63 | regiao = valor 64 | municipios[regiao] = {} 65 | elif nivel == self.ESTADO: 66 | estado = valor 67 | municipios[regiao][estado] = [] 68 | elif nivel == self.CIDADE: 69 | municipios[regiao][estado].append(valor) 70 | else: 71 | raise ParseError("Nível hierárquico inválido", linha) 72 | corrente = nivel 73 | else: 74 | raise ParseError("Hierarquia incorreta", linha) 75 | 76 | return municipios 77 | 78 | def __str__(self): 79 | """Retorna `lista de municípios` ao se imprimir o objeto.""" 80 | return "lista de municípios" 81 | 82 | 83 | def main(): 84 | try: 85 | brasil = Municipios(argv[1]) 86 | except ParseError as erro: 87 | # informa o erro e sai! 88 | print(erro) 89 | exit(1) 90 | else: 91 | # imprime os municípios do Rio de Janeiro. 92 | print(", ".join(brasil.municipios("Sudeste", "Rio de Janeiro"))) 93 | 94 | 95 | if __name__ == "__main__": 96 | main() 97 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/jquery.hotkeys.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery Hotkeys Plugin 3 | * Copyright 2010, John Resig 4 | * Dual licensed under the MIT or GPL Version 2 licenses. 5 | * 6 | * Based upon the plugin by Tzury Bar Yochay: 7 | * http://github.com/tzuryby/hotkeys 8 | * 9 | * Original idea by: 10 | * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ 11 | */ 12 | 13 | (function(jQuery){ 14 | 15 | jQuery.hotkeys = { 16 | version: "0.8", 17 | 18 | specialKeys: { 19 | 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20 | 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 21 | 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 22 | 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 23 | 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 24 | 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 25 | 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta" 26 | }, 27 | 28 | shiftNums: { 29 | "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", 30 | "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", 31 | ".": ">", "/": "?", "\\": "|" 32 | } 33 | }; 34 | 35 | function keyHandler( handleObj ) { 36 | // Only care when a possible input has been specified 37 | if ( typeof handleObj.data !== "string" ) { 38 | return; 39 | } 40 | 41 | var origHandler = handleObj.handler, 42 | keys = handleObj.data.toLowerCase().split(" "); 43 | 44 | handleObj.handler = function( event ) { 45 | // Don't fire in text-accepting inputs that we didn't directly bind to 46 | if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) || 47 | event.target.type === "text") ) { 48 | return; 49 | } 50 | 51 | // Keypress represents characters, not special keys 52 | var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[ event.which ], 53 | character = String.fromCharCode( event.which ).toLowerCase(), 54 | key, modif = "", possible = {}; 55 | 56 | // check combinations (alt|ctrl|shift+anything) 57 | if ( event.altKey && special !== "alt" ) { 58 | modif += "alt+"; 59 | } 60 | 61 | if ( event.ctrlKey && special !== "ctrl" ) { 62 | modif += "ctrl+"; 63 | } 64 | 65 | // TODO: Need to make sure this works consistently across platforms 66 | if ( event.metaKey && !event.ctrlKey && special !== "meta" ) { 67 | modif += "meta+"; 68 | } 69 | 70 | if ( event.shiftKey && special !== "shift" ) { 71 | modif += "shift+"; 72 | } 73 | 74 | if ( special ) { 75 | possible[ modif + special ] = true; 76 | 77 | } else { 78 | possible[ modif + character ] = true; 79 | possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true; 80 | 81 | // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" 82 | if ( modif === "shift+" ) { 83 | possible[ jQuery.hotkeys.shiftNums[ character ] ] = true; 84 | } 85 | } 86 | 87 | for ( var i = 0, l = keys.length; i < l; i++ ) { 88 | if ( possible[ keys[i] ] ) { 89 | return origHandler.apply( this, arguments ); 90 | } 91 | } 92 | }; 93 | } 94 | 95 | jQuery.each([ "keydown", "keyup", "keypress" ], function() { 96 | jQuery.event.special[ this ] = { add: keyHandler }; 97 | }); 98 | 99 | })( jQuery ); 100 | -------------------------------------------------------------------------------- /geradores-em-python/alfabeto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ Gera listas com sequências de letras do alfabeto, contém uma função 3 | convencional, `alfabeto_fn`, e um gerador, `alfabeto_gen`. """ 4 | 5 | 6 | PRIMEIRO, ULTIMO = "A", "Z" 7 | 8 | 9 | def alfabeto_fn(primeiro=PRIMEIRO, ultimo=ULTIMO, passo=1): 10 | """ Recebe o primeiro caractere em `primeiro` (ou "A"), último caractere 11 | da sequência em `ultimo` (ou "Z") e icremento da sequência em `passo` (ou 12 | 1). Retorna uma lista com a sequência de caracteres do primeiro ao último 13 | caractere aplicando o incremento definido. Invocará exceções de 14 | ValueError() nos casos do incremento ter valor 0 e os caracteres 15 | informados não estiverem em ordem crescente ou descrescente, de acordo com 16 | o incremento utilizado. """ 17 | 18 | primeiro = primeiro.upper() 19 | ultimo = ultimo.upper() 20 | 21 | alfabeto_list = [] 22 | 23 | caractere = ord(primeiro if primeiro > PRIMEIRO else PRIMEIRO) 24 | ultimo_caractere = ord(ultimo if ultimo < ULTIMO else ULTIMO) 25 | 26 | if passo == 0: 27 | raise ValueError("O valor de passo deve ser diferente de zero.") 28 | 29 | elif caractere > ultimo_caractere: 30 | if passo > 0: 31 | raise ValueError( 32 | "O último caractere deve ser maior que o primeiro quando o passo for positivo." 33 | ) 34 | else: 35 | while caractere >= ultimo_caractere: 36 | alfabeto_list.append(chr(caractere)) 37 | caractere += passo 38 | 39 | elif caractere < ultimo_caractere: 40 | if passo < 0: 41 | raise ValueError( 42 | "O último caractere deve ser menor que o primeiro quando o passo for negativo." 43 | ) 44 | else: 45 | while caractere <= ultimo_caractere: 46 | alfabeto_list.append(chr(caractere)) 47 | caractere += passo 48 | 49 | return alfabeto_list 50 | 51 | 52 | def alfabeto_gen(primeiro=PRIMEIRO, ultimo=ULTIMO, passo=1): 53 | """ (Gerador) Recebe o primeiro caractere em `primeiro` (ou "A"), último 54 | caractere da sequência em `ultimo` (ou "Z") e icremento da sequência em 55 | `passo` (ou 1). Retorna uma lista com a sequência de caracteres do 56 | primeiro ao último caractere aplicando o incremento definido. Invocará 57 | exceções de ValueError() nos casos do incremento ter valor 0 e os 58 | caracteres informados não estiverem em ordem crescente ou descrescente, 59 | de acordo com o incremento utilizado. """ 60 | 61 | primeiro = primeiro.upper() 62 | ultimo = ultimo.upper() 63 | 64 | caractere = ord(primeiro if primeiro > PRIMEIRO else PRIMEIRO) 65 | ultimo_caractere = ord(ultimo if ultimo < ULTIMO else ULTIMO) 66 | 67 | if passo == 0: 68 | raise ValueError("O valor de passo deve ser diferente de zero.") 69 | 70 | elif caractere > ultimo_caractere: 71 | if passo > 0: 72 | raise ValueError( 73 | "O último caractere deve ser maior que o primeiro quando o passo for positivo." 74 | ) 75 | else: 76 | while caractere >= ultimo_caractere: 77 | yield chr(caractere) 78 | caractere += passo 79 | 80 | elif caractere < ultimo_caractere: 81 | if passo < 0: 82 | raise ValueError( 83 | "O último caractere deve ser menor que o primeiro quando o passo for negativo." 84 | ) 85 | else: 86 | while caractere <= ultimo_caractere: 87 | yield chr(caractere) 88 | caractere += passo 89 | -------------------------------------------------------------------------------- /decoradores-em-python/decoradores.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Exemplo de decoradores 5 | """ 6 | 7 | 8 | def format_line(format_string, line_to_format, base_string=""): 9 | """ Formata uma linha da lista, recebe a _string_ a ser formatada em 10 | `format_string` e a lista contendo os dados em `line_to_format`. 11 | Retorna uma _string_ contendo os dados formatados. """ 12 | 13 | return base_string.join([format_string.format(cell) for cell in line_to_format]) 14 | 15 | 16 | def get_column_width(table_data): 17 | """ Verifica na tabela em `table_data` a célula mais larga na estrutura e 18 | define como a largura padrão da coluna. Retorna uma lista com a largura 19 | para cada coluna. """ 20 | 21 | width_temp = [] 22 | 23 | # navega na tabela de coluna em coluna. 24 | for column in range(len(table_data[0])): 25 | width_temp.append(max([len(str(cell[column])) for cell in table_data])) 26 | 27 | return width_temp 28 | 29 | 30 | def markdown(func_obj): 31 | """ (decorador) Formata uma lista em uma tabela em Markdown, recebe a 32 | função que produz a lista em `func_obj` e retorna a tabela formatada como 33 | uma _string_. """ 34 | 35 | def markdown_format(*args, **kwargs): 36 | """ Recupera os dados da função `func_obj` e formata uma lista 37 | em uma tabela Markdown. """ 38 | 39 | # recupera os valores gerados pela função. 40 | table_data = func_obj(*args, **kwargs) 41 | table_formated = "" 42 | table_width = get_column_width(table_data) 43 | 44 | # retira a primeira linha da lista para gerar a linha que separa 45 | # títulos e dados no cabeçalho das tabelas em markdown. 46 | temp_header = [ 47 | [cell.ljust(table_width[col]) for col, cell in enumerate(table_data.pop(0))] 48 | ] 49 | 50 | temp_header += [["-" * column for column in table_width]] 51 | 52 | for line in temp_header + table_data: 53 | table_formated += ( 54 | "|" 55 | + format_line( 56 | " {} |", 57 | [ 58 | str(cell).ljust(table_width[column]) 59 | for column, cell in enumerate(line) 60 | ], 61 | ) 62 | + "\n" 63 | ) 64 | 65 | return table_formated 66 | 67 | return markdown_format 68 | 69 | 70 | def html(func_obj): 71 | """ (decorador) Formata uma lista em uma tabela HTML, recebe a função 72 | que produz a lista em `func_obj` e retorna a tabela formatada como 73 | uma _string_. """ 74 | 75 | def html_format(*args, **kwargs): 76 | """ Recupera os dados da função `func_obj` e formata uma lista 77 | em uma tabela HTML. """ 78 | 79 | # recupera os valores gerados pela função. 80 | table_data = func_obj(*args, **kwargs) 81 | 82 | # converte a primeira linha da lista no cabeçalho, retirando-a 83 | # da lista. 84 | table_header = format_line(" {}", table_data.pop(0), "\n") 85 | 86 | # processa o corpo da tabela com o restante da lista. 87 | table_body = " \n" 88 | 89 | for line in table_data: 90 | table_body += ( 91 | " \n" + format_line(" {}", line, "\n") + "\n \n" 92 | ) 93 | 94 | table_body += " " 95 | 96 | # retorna os dados deviddamente formatados. 97 | return "\n \n \n{}\n \n \n{}\n
".format( 98 | table_header, table_body 99 | ) 100 | 101 | return html_format 102 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-3/municipios_tb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Exceções em Python - parte 3 (versão com traceback) """ 3 | # -*- coding: utf-8 -*- 4 | from sys import argv, stderr 5 | from traceback import print_exc 6 | 7 | EXIBE_TRACEBACK = True 8 | 9 | 10 | class ParseError(Exception): 11 | """A exceção customizada utilizada pelo 'parser'.""" 12 | 13 | def __init__(self, mensagem, linha=0): 14 | """Construtor da classe, recebe o texto do erro (mensagem) e 15 | também o número da linha onde ocorreu (opcional).""" 16 | self.mensagem = mensagem 17 | self.linha = linha 18 | 19 | def __str__(self): 20 | """Imprime a mensagem de erro.""" 21 | return "Erro: {}".format(self.mensagem) + \ 22 | (" na linha {}!".format(self.linha) if self.linha > 0 else "!") 23 | 24 | 25 | class Municipios(object): 26 | """Classe que armazena os municípios por região e estado.""" 27 | # esta classe só aceita três níveis hierárquicos 28 | REGIAO = 1 29 | ESTADO = 2 30 | CIDADE = 3 31 | 32 | def __init__(self, municipios): 33 | """Construtor da classe, recebe o nome do arquivo a ser lido.""" 34 | try: 35 | with open(municipios, "r") as arquivo: 36 | self.__municipios = self.__parser(arquivo) 37 | except FileNotFoundError: 38 | raise ParseError("Arquivo não encontrado") from FileNotFoundError 39 | 40 | @property 41 | def regioes(self): 42 | """Propriedade `regioes`, retorna as regiões existentes.""" 43 | return [i for i in self.__municipios.keys()] 44 | 45 | def estados(self, regiao): 46 | """Retorna os estados de uma região específica.""" 47 | return [i for i in self.__municipios[regiao].keys()] 48 | 49 | def municipios(self, regiao, estado): 50 | """Retorna os municípios de um determinado estado.""" 51 | return self.__municipios[regiao][estado] 52 | 53 | def __parser(self, arquivo): 54 | """Interpreta o arquivo texto e retorna os dados em um dicionário 55 | ou chamará a exceção `ParseError` caso ocorra algo de errado.""" 56 | corrente = linha = 0 57 | municipios = {} 58 | 59 | for itens in arquivo: 60 | linha += 1 61 | if itens is not "\n": 62 | nivel, valor = itens.strip().split(":") 63 | nivel = int(nivel) 64 | if nivel <= (corrente + 1): 65 | if nivel == self.REGIAO: 66 | regiao = valor 67 | municipios[regiao] = {} 68 | elif nivel == self.ESTADO: 69 | estado = valor 70 | municipios[regiao][estado] = [] 71 | elif nivel == self.CIDADE: 72 | municipios[regiao][estado].append(valor) 73 | else: 74 | raise ParseError("Nível hierárquico inválido", linha) 75 | corrente = nivel 76 | else: 77 | raise ParseError("Hierarquia incorreta", linha) 78 | 79 | return municipios 80 | 81 | def __str__(self): 82 | """Retorna `lista de municípios` ao se imprimir o objeto.""" 83 | return "lista de municípios" 84 | 85 | 86 | def main(): 87 | try: 88 | brasil = Municipios(argv[1]) 89 | except ParseError as erro: 90 | # informa o erro e sai! 91 | if EXIBE_TRACEBACK: 92 | print_exc(file=stderr) 93 | print(erro) 94 | exit(1) 95 | else: 96 | # imprime os municípios do Rio de Janeiro. 97 | print(", ".join(brasil.municipios("Sudeste", "Rio de Janeiro"))) 98 | 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /um-outro-exemplo-de-angularjs/exemplo-abj-2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 25 | 26 | 27 | Outro exemplo simples com AngularJS 28 | 29 | 30 | 31 | 32 | 33 |
34 |

Outro exemplo simples com AngularJS

35 |
36 |

Sem as mãos!

37 |

Mais um exemplo de AngularJS

38 |
39 | 42 |
43 |

Notas da turma

44 | 45 | 46 | 47 | 48 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 61 | 62 | 66 | 67 | 70 | 71 | 72 | 73 |
Aluno{{ bimestre }}º bimestreMédia
{{ aluno.nome | uppercase }}{{ nota | number:2 }}{{ boletim.mediaAritmetica( aluno.notas ) | number:2 }}
74 | 78 | Arquivo gerado automaticamente as {{ boletim.agora | date:'medium' }} 79 |
80 | 84 |
85 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /criando-imagens-em-python/mandelbrot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mandelbrot 3 | --- 4 | Este código foi convertido diretamente do MSX-BASIC (e esta de uma versão 5 | em Applesoft BASIC), logo o nome das variáveis e até um pouco da lógica 6 | estão um tanto quanto diferentes. 7 | 8 | O programa original pode ser encontrado em: 9 | https://www.retrocomputaria.com.br/2015/03/30/fractal-para-quem-precisa-de-fractal/ 10 | """ 11 | from PIL import Image 12 | from typing import Generator 13 | 14 | WIDTH = 768 15 | HEIGHT = 512 16 | 17 | # paleta original do exemplo em MSX2 18 | PALETTE = ( 19 | (0, 0, 0,), 20 | (1, 0, 1,), 21 | (2, 0, 2,), 22 | (4, 0, 4,), 23 | (5, 0, 5,), 24 | (7, 0, 7,), 25 | (7, 0, 6,), 26 | (7, 0, 5,), 27 | (7, 0, 3,), 28 | (7, 0, 2,), 29 | (7, 0, 0,), 30 | (7, 1, 0,), 31 | (7, 2, 0,), 32 | (7, 4, 0,), 33 | (7, 5, 0,), 34 | (7, 7, 0,), 35 | ) 36 | 37 | 38 | def convert_msx2_palette(palette) -> list: 39 | """ 40 | Converte as cores da paleta de 9-bit do MSX2 em 24-bit. 41 | """ 42 | new_palette = [] 43 | for color in palette: 44 | new_palette.append(tuple(map(lambda i: (i + 1) * 32 - 1, color))) 45 | 46 | return new_palette 47 | 48 | 49 | class Mandelbrot: 50 | """ 51 | Calcula um conjunto de Mandelbrot 52 | """ 53 | 54 | COLOR = 0xF # 16 cores 55 | ASCII = 0x1F # 32 caracteres 56 | 57 | # armazena a paleta de cores 58 | fake_palette = convert_msx2_palette(PALETTE) 59 | 60 | def __init__(self, iteractions: int, **kwargs) -> None: 61 | """ 62 | Inicializa a classe 63 | """ 64 | xc = kwargs.get("xc", -0.5) 65 | yc = kwargs.get("yc", 0.0) 66 | s = kwargs.get("s", 3.0) 67 | 68 | xr = s * 4 / 3 69 | yr = s 70 | 71 | self.x0 = xc - (xr / 2) 72 | self.x1 = xc + (xr / 2) 73 | self.y0 = yc - (yr / 2) 74 | self.y1 = yc - (yr / 2) 75 | 76 | self.xm = xr / WIDTH 77 | self.ym = yr / HEIGHT 78 | self.it = iteractions 79 | 80 | def __plot(self, x: int, y: int) -> int: 81 | """ 82 | Método que efetivamente desenha o fractal 83 | """ 84 | xx = x * self.xm + self.x0 85 | yy = y * self.ym + self.y0 86 | 87 | self.zx = self.zy = self.xx = self.yy = 0.0 88 | 89 | return self.__iteraction(xx, yy) 90 | 91 | def __iteraction(self, x: float, y: float) -> int: 92 | """ 93 | Faz as iterações do Mandelbrot, recebe as coordenadas (x,y) 94 | do pixel como `x` e `y` e retorna a "cor" dele. 95 | """ 96 | for i in range(self.it): 97 | self.zy = 2 * self.zx * self.zy + y 98 | self.zx = self.xx - self.yy + x 99 | self.xx = self.zx ** 2 100 | self.yy = self.zy ** 2 101 | 102 | color = self.it - i 103 | 104 | if self.xx + self.yy >= 4: 105 | break 106 | 107 | return color 108 | 109 | def to_png(self, width: int, height: int, filename: str) -> None: 110 | """ 111 | Gera um fractal de Mandelbrot como uma imagem. 112 | """ 113 | pillow_obj = Image.new("RGB", (width, height)) 114 | pixel_set = pillow_obj.load() 115 | 116 | for y in range(height): 117 | for x in range(width): 118 | 119 | color = self.__plot(x, y) & self.COLOR 120 | pixel_set[x, y] = self.fake_palette[color] 121 | 122 | pillow_obj.save(filename, "PNG") 123 | 124 | def to_ascii(self, width: int, height: int) -> str: 125 | """ 126 | Gera um fractal de Mandelbrot utilziando caracteres ASCII. 127 | """ 128 | output = "" 129 | 130 | for y in range(height): 131 | for x in range(width): 132 | # Usa somente os primeiros 32 primeiros caracteres 133 | color = self.__plot(x, y) & self.ASCII 134 | output += chr(31 + color) 135 | 136 | output += "\n" 137 | 138 | return output 139 | 140 | 141 | if __name__ == "__main__": 142 | # não faz muita coisa, instancia a classe e gera o arquivo 143 | mandel = Mandelbrot(50) 144 | mandel.to_png(WIDTH, HEIGHT, "pillow_fractal.png") 145 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Files from my blog 2 | 3 | There are here a set of programs and related files from my [blog](https://giovannireisnunes.wordpress.com) posts. All posts are written in Brazilian Portuguese but you're invited to know them -- even using some kind of language translator :-) 4 | 5 | # Arquivos do meu blog 6 | 7 | Aqui estão os arquivos e outras coisas citados e/ou utilizados nas publicações do meu [blog](https://giovannireisnunes.wordpress.com). 8 | 9 | ## Publicações relacionadas 10 | 11 | Os mais recentes primeiro (ordem é cronológica invertida). 12 | 13 | ### 2023 14 | * Convertendo imagens para o Atari ST [parte1](https://giovannireisnunes.wordpress.com/2023/12/23/convertendo-imagens-para-o-atari-st-parte-1/) 15 | 16 | ### 2022 17 | * Usando o pydantic [parte 1](https://giovannireisnunes.wordpress.com/2022/08/26/usando-o-pydantic-parte---1) 18 | 19 | ### 2021 20 | * [Incrementando o Tetris do MSX1](https://giovannireisnunes.wordpress.com/2021/12/31/incrementando-o-tetris-do-msx1/) 21 | * [Convertendo imagens em 16 cores no MSX - parte 2](https://giovannireisnunes.wordpress.com/2021/10/22/convertendo-imagens-em-16-cores-no-msx---parte-2) 22 | * [Convertendo imagens em 16 cores no MSX - parte 1](https://giovannireisnunes.wordpress.com/2021/04/16/convertendo-imagens-em-16-cores-no-msx) 23 | * [Manipulando XLSX em Python](https://giovannireisnunes.wordpress.com/2021/02/19/manipulando-xlsx-em-python/) 24 | 25 | ### 2020 26 | * [Convertendo imagens para MSX](https://giovannireisnunes.wordpress.com/2020/08/28/convertendo-imagens-para-msx) 27 | * [Usando arquivos CSV em Python](https://giovannireisnunes.wordpress.com/2020/07/17/usando-arquivos-csv-em-python) 28 | * [Mais decoradores em Python](https://giovannireisnunes.wordpress.com/2020/04/03/mais-decoradores-em-python/) 29 | * [Orientação a objetos em Python, além do básico](https://giovannireisnunes.wordpress.com/2020/03/20/orientacao-a-objetos-em-python-alem-do-basico) 30 | * [Criando imagens em Python](https://giovannireisnunes.wordpress.com/2020/01/24/criando-imagens-em-python) 31 | 32 | ### 2019 33 | * [Decoradores em Python](https://giovannireisnunes.wordpress.com/2019/04/12/decoradores-em-python) 34 | * [Geradores em Python](https://giovannireisnunes.wordpress.com/2019/02/22/geradores-em-python) 35 | 36 | ### 2018 37 | * [Cobertura de código com pytest](https://giovannireisnunes.wordpress.com/2018/11/30/cobertura-de-codigo-com-pytest) 38 | * [Argumentos de funções em Python](https://giovannireisnunes.wordpress.com/2018/10/12/argumentos-de-funcoes-em-python) 39 | * [Registro de eventos em Python](https://giovannireisnunes.wordpress.com/2018/09/28/registro-de-eventos-em-python) 40 | * [Um básico de pytest](https://giovannireisnunes.wordpress.com/2018/09/14/um-basico-de-pytest) 41 | * [Usando grupos em expressões regulares](https://giovannireisnunes.wordpress.com/2018/08/24/usando-grupos-em-expressoes-regulares) 42 | * Exceções em Python - [parte 1](https://giovannireisnunes.wordpress.com/2018/06/22/excecoes-em-python-parte-1), [parte 2](https://giovannireisnunes.wordpress.com/2018/06/29/excecoes-em-python-parte-2) e [parte 3](https://giovannireisnunes.wordpress.com/2018/07/13/excecoes-em-python-parte-3) 43 | 44 | ### 2017 45 | * [Módulos em Python](https://giovannireisnunes.wordpress.com/2017/08/18/modulos-em-python) 46 | 47 | ### 2016 48 | * [Orientação a objetos em JavaScript, o básico](https://giovannireisnunes.wordpress.com/2016/12/23/orientacao-a-objetos-em-javascript-o-basico/) 49 | * [Orientação a objetos em Python, o básico](https://giovannireisnunes.wordpress.com/2016/11/25/orientacao-a-objetos-em-python-o-basico/) 50 | * [Orientação a objetos em Ruby, o básico](https://giovannireisnunes.wordpress.com/2016/10/07/orientacao-a-objetos-em-ruby-o-basico) 51 | 52 | ### 2015 53 | * [Orientação a objetos em PHP, o básico](https://giovannireisnunes.wordpress.com/2015/08/07/orientacao-a-objetos-em-php-o-basico/) 54 | * [Um outro exemplo de AngularJS](https://giovannireisnunes.wordpress.com/2015/07/31/um-outro-exemplo-de-angularjs/) 55 | * [Exemplo com AngularJS, Bootstrap e jQuery](https://giovannireisnunes.wordpress.com/2015/07/23/exemplo-com-angularjs-bootstrap-e-jquery/) 56 | * [Orientação a objetos em Perl, o básico](https://giovannireisnunes.wordpress.com/2015/06/26/um-basico-de-orientacao-a-objetos-em-perl/) 57 | * [Gerador de arquivos IPS](https://giovannireisnunes.wordpress.com/2015/06/14/gerador-de-arquivos-ips/) 58 | * XML em Perl - [parte 3](https://giovannireisnunes.wordpress.com/2015/06/05/xml-em-perl-parte-3/) 59 | * [Máquina virtual em Perl](https://giovannireisnunes.wordpress.com/2015/06/01/maquina-virtual-em-perl/) 60 | * [Faxina no /boot](https://giovannireisnunes.wordpress.com/2015/05/25/faxina-no-boot/) 61 | * [Quantos dias tem o mês?](https://giovannireisnunes.wordpress.com/2015/05/01/quantos-dias-tem-um-mes/) 62 | 63 | ## Para os arquivos 64 | 65 | Todos os programas estão licenciados na **GPL**, mesmo que eu tenha esquecido de informar, podem ser utilizados livremente (desde que não violem os termos da licença, é claro) e é possível baixá-los diretamente pela interface web do __GitHub__ ou então através do próprio `git`: 66 | 67 | ``` 68 | $ git clone https://github.com/plainspooky/giovannireisnunes.git 69 | ``` 70 | 71 | Precisando de ajuda para instalar e/ou utilizar a ferramenta consulte o [git - guia prático](https://rogerdudler.github.io/git-guide/index.pt_BR.html). 72 | 73 | E precisando de algo mais detalhado sobre o **Git**, tente [aqui](https://giovannireisnunes.wordpress.com/2016/07/08/usando-o-git-parte-1/). 74 | -------------------------------------------------------------------------------- /xml-em-perl-parte-3/ped.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # Ped 1.0 4 | # It is a example of how to get a lot of XML files generated by 5 | # Fitness++ (from Apple's iPod Nano 6th gen) process them and display 6 | # a fancy output -- https://giovannireisnunes.wordpress.com/?p=177 7 | # 8 | # Copyright 2015, Giovanni Nunes 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 2 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software 22 | # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 23 | # MA 02110-1301, USA. 24 | # 25 | use strict; 26 | use XML::Simple; 27 | 28 | use constant PROGRAM => 'Ped'; 29 | use constant UPDATE => 'atualizar'; 30 | use constant SHOW => 'exibir'; 31 | use constant STEPS => 'passadas'; 32 | use constant HTML => 'html'; 33 | 34 | use constant SUMMARY => 'ped.xml'; 35 | use constant T_TEXT => 'ped.ptxt'; 36 | use constant T_HTML => 'ped.phtml'; 37 | 38 | my $xml=new XML::Simple; 39 | 40 | my $ped={}; 41 | 42 | my ( $i, $j, $k ); 43 | my ( $workouts, $farthest, $rundistance, $time, $calories, $walking, $running, $mysteps ); 44 | my ( $xmlfile, $fh, $fs, $data, $output, $content ); 45 | 46 | if ( -f SUMMARY ) 47 | { 48 | $ped=$xml->XMLin(SUMMARY); 49 | $mysteps=$ped->{Summary}{MyStep}; 50 | $j=1; 51 | } 52 | else 53 | { 54 | $j=0; 55 | } 56 | 57 | my $Command=$ARGV[0]; 58 | my $Parameter=$ARGV[1]; 59 | 60 | if ( $Command eq UPDATE or $Command eq STEPS ) 61 | { 62 | foreach $xmlfile (`ls data/[0-9]*.xml`) 63 | { 64 | $fh = IO::File->new($xmlfile); 65 | $data=$xml->XMLin($fh); 66 | 67 | if ( $Command eq UPDATE ) 68 | { 69 | $workouts++; 70 | 71 | $i=$data->{runSummary}{distance}{content}; 72 | $j=$data->{runSummary}{stepCounts}{walkEnd}-$data->{runSummary}{stepCounts}{walkBegin}; 73 | $k=$data->{runSummary}{stepCounts}{runEnd}-$data->{runSummary}{stepCounts}{runBegin}; 74 | $i=($j+$k)*($mysteps/1000) if ( $i==undef ); 75 | $farthest=$i if ( $i>$farthest ); 76 | $rundistance+=$i; 77 | $time+=$data->{runSummary}{duration}; 78 | $calories+=$data->{runSummary}{calories}; 79 | $walking+=$j; 80 | $running+=$k; 81 | } 82 | else 83 | { 84 | $i=$data->{runSummary}{distance}{content}; 85 | if ( $i>0 ) 86 | { 87 | $j++; 88 | $k+=$i/($data->{runSummary}{stepCounts}{walkEnd}-$data->{runSummary}{stepCounts}{walkBegin})+($data->{runSummary}{stepCounts}{runEnd}-$data->{runSummary}{stepCounts}{runBegin}); 89 | } 90 | } 91 | } 92 | if ( $Command eq UPDATE ) 93 | { 94 | $ped->{Summary}={ Workouts => $workouts, 95 | Farthest => $farthest, 96 | RunDistance => $rundistance, 97 | Time => $time/1000, 98 | Calories => $calories, 99 | Walking => $walking, 100 | Running => $running, 101 | TotalSteps => ($walking+$running), 102 | MyStep => $mysteps }; 103 | 104 | print "Histórico atualizado, totalizando $workouts exercício(s)\n"; 105 | } 106 | else 107 | { 108 | $mysteps=sprintf('%.5f',1000*($k/$j)); 109 | $ped->{Summary}{MyStep}=$mysteps; 110 | 111 | print "Utilizado(s) $j registro(s) para o cálculo.\nUm passo equivale a $mysteps metro(s).\n"; 112 | } 113 | 114 | open($fh,'>'.SUMMARY); 115 | print $fh $xml->XMLout($ped); 116 | close($fh); 117 | } 118 | elsif( $Command eq SHOW ) 119 | { 120 | if ( $j>0 ) 121 | { 122 | $i=$ped->{Summary}{Time}; 123 | 124 | my $hours=int($i/3600); 125 | my $minutes=int($i/60)-$hours*60; 126 | my $seconds=$i-$minutes*60-$hours*3600; 127 | 128 | if ( $Parameter eq HTML ) 129 | { 130 | $output=T_HTML; 131 | } 132 | else 133 | { 134 | $output=T_TEXT; 135 | } 136 | 137 | open($fh,'<',$output ); 138 | $fs=-s $output; 139 | read $fh,$content,$fs; 140 | close($fh); 141 | 142 | $content=~s/%_WORKOUTS_%/$ped->{Summary}{Workouts}/; 143 | 144 | $i=sprintf('%.2f',$ped->{Summary}{Farthest}); 145 | $content=~s/%_FARTHEST_%/$i/; 146 | 147 | $i=sprintf('%.2f',$ped->{Summary}{RunDistance}); 148 | $content=~s/%_RUNDISTANCE_%/$i/; 149 | 150 | $content=~s/%_TOTALHOU_%/$hours/; 151 | $content=~s/%_TOTALMIN_%/$minutes/; 152 | 153 | $i=sprintf('%.2f',$seconds); 154 | $content=~s/%_TOTALSEC_%/$i/; 155 | 156 | $content=~s/%_CALORIES_%/$ped->{Summary}{Calories}/; 157 | $content=~s/%_TOTALSTEPS_%/$ped->{Summary}{TotalSteps}/; 158 | $content=~s/%_WALKING_%/$ped->{Summary}{Walking}/; 159 | $content=~s/%_RUNNING_%/$ped->{Summary}{Running}/; 160 | $content=~s/%_MYSTEPS_%/$ped->{Summary}{MyStep}/; 161 | 162 | print $content; 163 | } 164 | else 165 | { 166 | print "Sem histórico registrado, utilize '".UPDATE."' primeiro.\n"; 167 | } 168 | } 169 | else 170 | { 171 | print PROGRAM." - sumariza os arquivos XML produzidos pelo programa Fitness++ ". 172 | "dos iPod Nano 6th generation.\n". 173 | "Utilize:\n ". 174 | UPDATE." - atualiza o histórico de exercícios.\n ". 175 | SHOW." - exibe o histórico de exercícios\n ". 176 | SHOW." ".HTML." - para o histórico em HTML.\n ". 177 | STEPS." - para calcular a passada média.\n" 178 | } 179 | 180 | exit 0; 181 | -------------------------------------------------------------------------------- /exemplo-com-angularjs-bootstrap-e-jquery/exemplo-abj.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | /* 3 | * Exemplo ABj 1.0 4 | * 5 | * Exemplo de página web com AngularJS, Bootstrap e jQuery 6 | * 7 | * Copyright 2015, Giovanni Nunes 8 | * 9 | * This program is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by 11 | * the Free Software Foundation; either version 2 of the License, or 12 | * (at your option) any later version. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License 20 | * along with this program; if not, write to the Free Software 21 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 22 | * MA 02110-1301, USA. 23 | * 24 | */ 25 | 26 | /* 27 | * minha aplicação (portifolio) é definida aqui e os demais controles vão 28 | * concatenados na variável 'app'. 29 | */ 30 | var app=angular.module('exemplo',[]) 31 | .controller("TituloController",function() { 32 | this.texto=titulo; 33 | }) 34 | /* 35 | * cuida de preencher o título em ... 36 | */ 37 | .controller('MenuController',function() { 38 | this.pagina=0; 39 | this.texto=titulo; 40 | /* 41 | * altera o valor da variável 'pagina' (a aba ativa). 42 | */ 43 | this.escolhePagina = function(pag) { 44 | this.pagina=pag; 45 | }; 46 | /* 47 | * retorna 'true' ou 'false' se o valor informado é o da aba ativa. 48 | */ 49 | this.verificaPagina = function(pag) { 50 | return this.pagina === pag; 51 | }; 52 | }) 53 | /* 54 | * preenche do conteúdo dentro do jumbotron da página 55 | */ 56 | .controller('JumboController',function() { 57 | this.conteudo=website["jumbo"]; 58 | }) 59 | /* 60 | * responsável pelos três botões explicativos 61 | */ 62 | .controller('ResumoController',function() { 63 | this.conteudos=website["conteudo"]; 64 | }) 65 | /* 66 | * preeenche o conteúdo do sobre 67 | */ 68 | .controller('SobreController',function() { 69 | this.conteudo=website["sobre"]; 70 | this.license=gpl; 71 | }); 72 | 73 | /* 74 | * esta variável guarda o título to projeto 75 | */ 76 | var titulo="Um exemplo bem simples com AngularJS, Bootstrap e jQuery"; 77 | 78 | /* 79 | * no mundo real este conteúdo poderia ser carregado diretamente de 80 | * um arquivo 'json' via http -- via Service -- mas aqui vai como um 81 | * hash em JavaScript mesmo. 82 | */ 83 | var website={ 84 | 'jumbo':{ 85 | 'texto':'Funciona!', 86 | 'descr':'Veja o código fonte e compare com o que está na tela', 87 | 'botao':'Baixe os arquivos aqui!', 88 | 'link':'https://github.com/plainspooky/giovannireisnunes/blob/master/README.md' 89 | }, 90 | 'conteudo': [ { 91 | 'titulo':'AngularJS', 92 | 'texto': 'AngularJS é um framework open-source para a desenvolvimento de aplicações web.'+ 93 | ' Foi criado pelo Google e hoje é mantido por este e uma comunidade de desenvolvedores independentes.', 94 | 'tela': 'https://giovannireisnunes.files.wordpress.com/2015/07/angular.jpeg', 95 | 'link': 'http://www.angularjs.org' 96 | }, { 97 | 'titulo':'Bootstrap', 98 | 'texto': 'Bootstrap é um framework open-source para HTML, CSS e JavaScript desenvolvido'+ 99 | ' pelo Twitter para a criação rápida e do zero de sítios web responsivos ou móveis.', 100 | 'tela': 'https://giovannireisnunes.files.wordpress.com/2015/07/bootstrap.jpeg', 101 | 'link': 'http://getbootstrap.com/' 102 | }, { 103 | 'titulo':'jQuery', 104 | 'texto': 'jQuery é uma biblioteca em JavaScript para a manipulação dos elementos HTML.'+ 105 | ' Acrescenta recursos como animação, tratamento de eventos e AJAX em uma API simplificada.', 106 | 'tela': 'https://giovannireisnunes.files.wordpress.com/2015/07/jquery.jpeg', 107 | 'link': 'http://jquery.com/' 108 | } 109 | ], 110 | 'sobre': { 111 | 'titulo':'Sobre', 112 | 'texto':'Este é um pequeno exemplo do que se pode fazer juntando estas três ferramentas'+ 113 | ' (Angular.JS, Bootstrap e jQuery) na forma de um exercício de programação para'+ 114 | ' praticar o que aprendi nos cursos de AngularJS do Codecademy e do Codeschool'+ 115 | ' (sim eu fiz ambos).' 116 | } 117 | }; 118 | /* 119 | * As cadeias de caracteres estão concatenadas e não apenas unidas com "\" para não 120 | * colocar conteúdo extra no texto (e obviamente deixá-las um pouco mais legíveis), justamente 121 | * o inverso do que fiz na variável abaixo: 122 | */ 123 | var gpl="Exemplo-ABj 1.0\n\ 124 | \n\ 125 | Exemplo de página web com AngularJS, Bootstrap e jQueryz\n\ 126 | \n\ 127 | This program is free software; you can redistribute it and/or modify\n\ 128 | it under the terms of the GNU General Public License as published by\n\ 129 | the Free Software Foundation; either version 2 of the License, or\n\ 130 | (at your option) any later version.\n\ 131 | \n\ 132 | This program is distributed in the hope that it will be useful,\n\ 133 | but WITHOUT ANY WARRANTY; without even the implied warranty of\n\ 134 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\ 135 | GNU General Public License for more details.\n\ 136 | \n\ 137 | You should have received a copy of the GNU General Public License\n\ 138 | along with this program; if not, write to the Free Software\n\ 139 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n\ 140 | MA 02110-1301, USA." 141 | 142 | })(); 143 | -------------------------------------------------------------------------------- /excecoes-em-python-parte-2/CavaleiroNegro.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | def imprime(): 3 | 4 | # paleta de 48 cores produzida de um arquivo XPM. 5 | colors = { 6 | " ": "09080E", ".": "0E0906", "+": "210D0D", "@": "1F191F", 7 | "#": "251914", "$": "362220", "j": "551A17", "&": "2A262B", 8 | "*": "2F2622", "=": "2C2538", "-": "422E21", ";": "48302F", 9 | ">": "393345", ",": "3E342E", "'": "3A353C", ")": "523D3D", 10 | "!": "863128", "~": "484141", "{": "4E4238", "]": "45434E", 11 | "^": "663C33", "/": "594938", "(": "5D4B4E", "_": "9E3D33", 12 | ":": "575351", "<": "5E5247", "[": "635F66", "}": "6A5F5A", 13 | "|": "60625A", "1": "775F53", "2": "756656", "3": "67725B", 14 | "4": "7B6E68", "5": "6F7369", "6": "717177", "7": "897B7C", 15 | "8": "8D7D6F", "9": "7D8085", "0": "80817B", "a": "828775", 16 | "b": "9E8C80", "c": "8C918C", "d": "978E8D", "e": "9FA09E", 17 | "f": "B09F99", "g": "AEA38B", "h": "ADB3B1", "i": "CACECE", 18 | } 19 | 20 | # tabela de atributos produzida de um arquiovo XPM. 21 | attributes = [ 22 | ">>]>]]>>'>>']']]]]'=>='@@~~:'@&'@'=]]']]']~~'~~~~']]]'&&~~~'~'''''~[|5e9:a5|5===", 23 | ">>>>>''>>>>'''>>'''@= 'iiii@@&==]]~~~'''~,~,,~~'&&. '({(<)<:}}4}::95[]chc[>>>", 24 | "]]]]~']>')))''~]]]~'= $-$-$~&&==>~~::~{{{{{))~;& .::::<::}}|}[}[::]]]:[>>>>", 25 | "[[|[||:[|:}[::}((:(&= @~..##,*.===~:(::|<|<}<:}:'@ .{{<<<}}}||||||:::~~~]>'=>", 26 | "69996469666990dcd70'@ &::{,;, ===33333|}}[}|}' @.. @=&:<|<|:|}||||::::~:]~::", 27 | "[[::[[[[[~]:[[5|c|5'&&@:{||<--{ ===~5||{:::[66[ $.j!. .. }|}}[}}44}455||33055[[", 28 | "6[[[[[[[6[6699de00~$+j;::ci#$-/ @===aa0a0cc9c9: _!_! .. ~0444}55553a55574746}||", 29 | "66696666669990cc:6&;@~~hh05*$--e ===cccceeee9e +jjj ...eacacaaaaa3a3a3333333|[", 30 | "6966664966666470|:,$*&~$hc5|$$/e &>>>([::569|99. . ...hieefeddeecdefhehedd999", 31 | "[[[[[[[[[79|[[[[' @'*&$#00c|##}[ ([4444}656|}. .. eeddd7cdac07ddddddd9d99", 32 | "[[([[[[[[}[}{}:::~'& ..#-+&~~@-/,.,:|444422484 .. .. d0cccddabd0070047676[6[", 33 | "~''~~::|{{***&*#*,*,,*,,q\"Q:Q:7z.--\"ugz2jzrQ}:(Q::ajg@@@QQapj:;'';;;(222@$@@@QjpQR@@Cj$@:o&Y", 62 | "a\\jj\\jj2a2jj2j2j;__jpQj::gz2jz\\QL.jGnZ:0:Q@ppj2jj..._;;{jaa2cQj22Qj@@QQQjjpQz\"\":", 63 | ":\":2jjazZ:Qggzj\\2\\j:@@'qjgz2zg2@j\\\\:::::\\.\"=C$Qp2'qj$Lj7@2j2r@jQ2p:o\\2@j@@@CQQ::", 64 | "Q@#\"@::j\"jajjj2z\"Cj\\j::qagz2zgajjcp@j:75Caj\\J:jpQ:Qjj2,jq22\\j\\2j@QQQ2a\"--::-oQQ:", 65 | "zzZQj.:@:#$:Q@N#::@::2\"{zgz2ggzjjg_;@#r:jjj;;-Y+z1j2jjpj1jjjjj\\j$@C2p:Q__._..QQQ", 66 | "..._.J....._____\\_122jjgzZguQgQjjz\\pQ.\"jjjj1t..$jqQjjjj:1jpjjjjj@jQ0HKjC2j\\jjQ\\$", 67 | "jjjjj2au2222j2azzzau2uar-\"q2=5\">4j2auuajjj\\2@#+q_:$@@$;gQ2::j;\"o9090=u:e@AsAKEEQ", 68 | "jrjjjjjjjjj2C2222j22222pNquu.2}2{uj2j222j2j2jjQMA2:c2r::_a1zQ:y#zaj::7\"uS&::2:Qg", 69 | "Q@j@jjjQjjj2jj\\jj2222j2$2-jjj@lg{jQj@j@p@@j$QQQQQQ::QgzZ2jy=!.j_._\\\\j2j\\:2zg:K:Q", 70 | ] 71 | 72 | knight = "" 73 | 74 | for lin in range(0, len(pattern)): 75 | for col in range(0, len(pattern[lin])): 76 | atr = colors[attributes[lin][col]] 77 | (red, green, blue) = (int(atr[i:i+2], base=16) 78 | for i in range(0, 6, 2)) 79 | knight += "\x1b[38;2;{};{};{}m{}\x1b[0m".format( 80 | red, green, blue, pattern[lin][col]) 81 | knight += "\n" 82 | 83 | return knight 84 | -------------------------------------------------------------------------------- /convertendo-imagens-para-16-cores-do-msx/functions.py: -------------------------------------------------------------------------------- 1 | """Funções de uso geral.""" 2 | try: 3 | # para versões do python >= 3.9 4 | from functools import cache 5 | except ModuleNotFoundError: 6 | # para as versões < 3.9 7 | from functools import lru_cache as cache 8 | 9 | from math import sqrt 10 | 11 | from divisiblelist import DivisibleList 12 | 13 | BPP_MASK = 0xE0 14 | 15 | FLOYD_STEINBERG_NEIGHBORS = ( 16 | (+1, 0, 7), 17 | (-1, +1, 3), 18 | (-1, +1, 5), 19 | (+1, +1, 1), 20 | ) 21 | 22 | # a paleta padrão do MSX 23 | MSX_DEFAULT_PALETTE = [ 24 | (0, 0, 0), 25 | (0, 0, 0), 26 | (32, 192, 32), 27 | (96, 224, 96), 28 | (32, 32, 224), 29 | (64, 96, 224), 30 | (160, 32, 32), 31 | (64, 192, 224), 32 | (224, 32, 32), 33 | (224, 96, 96), 34 | (192, 192, 32), 35 | (192, 192, 128), 36 | (32, 128, 32), 37 | (192, 64, 160), 38 | (160, 160, 160), 39 | (224, 224, 224), 40 | ] 41 | 42 | # estes lambdas estão aqui não precisar replicá-los no código 43 | color_key = lambda color: color[0] 44 | color_value = lambda color: color[1] 45 | 46 | 47 | def add_noise(bitmap, x, y, error): 48 | """Adiciona ruído nos pixeis vizinhos aplicando a diferença nos 49 | valores RGB da cor original e seu valor após a redução.""" 50 | for offset_x, offset_y, debt in FLOYD_STEINBERG_NEIGHBORS: 51 | try: 52 | # calcula o endereço do pixel a ser alterado 53 | off_x, off_y = x + offset_x, y + offset_y 54 | # adiciona o ruído definido pelo Floyd-Steinberg ao pixel 55 | bitmap[off_x, off_y] = tuple( 56 | ( 57 | color + error * debt // 16 58 | for color, error in zip(bitmap[off_x, off_y], error) 59 | ) 60 | ) 61 | except IndexError: 62 | # trata o caso de um vizinho fora da área da imagem 63 | ... 64 | 65 | 66 | def bsave(filename, data, start=0): 67 | """ 68 | Monta o cabeçalho e salva um arquivo no formato binário do MSX-BASIC. 69 | """ 70 | 71 | size = len(data) - 1 72 | stop = start + size 73 | 74 | # acrescenta o cabeçalho e salva o conteúdo em um arquivo. 75 | with open(filename, "wb") as f: 76 | f.write(b"\xfe") 77 | for i in (start, stop, start): 78 | f.write(i.to_bytes(length=2, byteorder="little")) 79 | f.write(data) 80 | 81 | 82 | def convert_palette(palette): 83 | """Converte a palete para um formato mais fácil de trabahar no MSX.""" 84 | data = bytearray() 85 | 86 | for r, g, b in palette: 87 | r //= 2 88 | g //= 32 89 | b //= 32 90 | data += bytes([r + b, b]) 91 | 92 | return data 93 | 94 | 95 | def convert_to_vram(screen): 96 | """converte a imagem no padrão de 16 cores da VRAM do MSX.""" 97 | vram = bytearray() 98 | 99 | for line in screen: 100 | # separa cada linha em pedaços com dois itens e forma um byte. 101 | vram += bytearray( 102 | (even * 16 + odd for even, odd in DivisibleList(line) / {2}) 103 | ) 104 | 105 | return vram 106 | 107 | 108 | def count_colors(image): 109 | """Calcula a frequência de cada pixel da imagem em uma paleta RGG de 110 | 9-bit.""" 111 | 112 | bitmap = image.load() 113 | colors = {} 114 | 115 | for y in range(image.height): 116 | for x in range(image.width): 117 | # extrai os componentes RGB e reduz os elementos de cor 118 | # (ignora o canal alfa caso ele exista) 119 | r, g, b, *__ = bitmap[x, y] 120 | 121 | # corta a parte não necessária (mais prático que ÷ e depois ×) 122 | r &= BPP_MASK 123 | g &= BPP_MASK 124 | b &= BPP_MASK 125 | 126 | # monta a frequência de cores da imagem 127 | colors[(r, g, b)] = colors.get((r, g, b), 1) + 1 128 | 129 | # organiza o dicionário para uma lista de tuplas 130 | return [(k, v) for k, v in colors.items()] 131 | 132 | 133 | def distance(origin, destination): 134 | """Calcula a distância entre dois pontos num espaço euclidiano de três 135 | dimensões.""" 136 | 137 | # ignora os canais alfa caso existam 138 | r1, g1, b1, *__ = origin 139 | r2, g2, b2, *__ = destination 140 | 141 | return sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2) 142 | 143 | 144 | def quantize_colors(palette, length): 145 | """Reduz o número de cores de uma imagem até o valor desejado.""" 146 | 147 | # enquanto a paleta for maior que o valor desejado, faça... 148 | while len(palette) > length: 149 | # ordena a paleta em ordem crescente de frequência 150 | palette.sort(key=color_value) 151 | 152 | # recupera a 1ª cor e calcula a distância delas para as demais 153 | color, freq = palette.pop(0) 154 | 155 | # monta a lista de distância da cor lida para com as demais 156 | distances = [ 157 | (idx, distance(color, clr[0])) 158 | for idx, clr in enumerate(palette[1:], start=1) 159 | ] 160 | 161 | # a nova cor é a de menor ocorrência, recupera seu índice 162 | index, __ = min(distances, key=color_value) 163 | 164 | # adiciona as ocorrências da cor antiga à nova e a remove da lista 165 | palette[index] = ( 166 | palette[index][0], 167 | palette[index][1] + freq, 168 | ) 169 | 170 | # retorna apenas as cores da paleta 171 | return [i[0] for i in sorted(palette, key=color_key)] 172 | 173 | 174 | def reduce_colors(image, palette, dither=True): 175 | """Faz a redução do número de cores de uma imagem aplicando, ou não 176 | _dithering_.""" 177 | 178 | @cache 179 | def match_color(pixel): 180 | """Procura a cor mais próxima dentro da paleta de cores.""" 181 | 182 | return min( 183 | [(idx, distance(pixel, clr)) for idx, clr in enumerate(palette)], 184 | key=color_value, 185 | )[0] 186 | 187 | bitmap = image.load() 188 | 189 | # os índices em uma sequência 190 | screen = DivisibleList() 191 | 192 | for y in range(image.height): 193 | line = [] 194 | for x in range(image.width): 195 | # recupera o valor do pixel 196 | pixel = bitmap[x, y] 197 | 198 | # verifica se a cor existe no cac/he 199 | index = match_color(pixel) 200 | 201 | # atualiza o pixel com a nova cor 202 | bitmap[x, y] = palette[index] 203 | 204 | # salva o índice de cor 205 | line.append(index) 206 | 207 | if dither: 208 | # adiciona ruído nos pixeis vizinhos 209 | error = [old - new for old, new in zip(pixel, palette[index])] 210 | add_noise(bitmap, x, y, error) 211 | 212 | screen.append(line) 213 | 214 | return screen 215 | 216 | 217 | def split_pages(screen): 218 | """Divide a tela entre linhas pares e ímpares.""" 219 | 220 | first_page, second_page = [], [] 221 | 222 | for even_line, odd_line in screen / {2}: 223 | # distribui cada linha em duas páginas. 224 | first_page.append(even_line) 225 | second_page.append(odd_line) 226 | 227 | return first_page, second_page 228 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/style.css: -------------------------------------------------------------------------------- 1 | /* Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 */ 2 | /* For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt */ 3 | 4 | /* CSS styles for coverage.py. */ 5 | 6 | /* Page-wide styles */ 7 | html, body, h1, h2, h3, p, table, td, th { 8 | margin: 0; 9 | padding: 0; 10 | border: 0; 11 | outline: 0; 12 | font-weight: inherit; 13 | font-style: inherit; 14 | font-size: 100%; 15 | font-family: inherit; 16 | vertical-align: baseline; 17 | } 18 | 19 | /* Set baseline grid to 16 pt. */ 20 | body { 21 | font-family: georgia, serif; 22 | font-size: 1em; 23 | } 24 | 25 | html>body { 26 | font-size: 16px; 27 | } 28 | 29 | /* Set base font size to 12/16 */ 30 | p { 31 | font-size: .75em; /* 12/16 */ 32 | line-height: 1.33333333em; /* 16/12 */ 33 | } 34 | 35 | table { 36 | border-collapse: collapse; 37 | } 38 | td { 39 | vertical-align: top; 40 | } 41 | table tr.hidden { 42 | display: none !important; 43 | } 44 | 45 | p#no_rows { 46 | display: none; 47 | font-size: 1.2em; 48 | } 49 | 50 | a.nav { 51 | text-decoration: none; 52 | color: inherit; 53 | } 54 | a.nav:hover { 55 | text-decoration: underline; 56 | color: inherit; 57 | } 58 | 59 | /* Page structure */ 60 | #header { 61 | background: #f8f8f8; 62 | width: 100%; 63 | border-bottom: 1px solid #eee; 64 | } 65 | 66 | #source { 67 | padding: 1em; 68 | font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; 69 | } 70 | 71 | .indexfile #footer { 72 | margin: 1em 3em; 73 | } 74 | 75 | .pyfile #footer { 76 | margin: 1em 1em; 77 | } 78 | 79 | #footer .content { 80 | padding: 0; 81 | font-size: 85%; 82 | font-family: verdana, sans-serif; 83 | color: #666666; 84 | font-style: italic; 85 | } 86 | 87 | #index { 88 | margin: 1em 0 0 3em; 89 | } 90 | 91 | /* Header styles */ 92 | #header .content { 93 | padding: 1em 3em; 94 | } 95 | 96 | h1 { 97 | font-size: 1.25em; 98 | display: inline-block; 99 | } 100 | 101 | #filter_container { 102 | display: inline-block; 103 | float: right; 104 | margin: 0 2em 0 0; 105 | } 106 | #filter_container input { 107 | width: 10em; 108 | } 109 | 110 | h2.stats { 111 | margin-top: .5em; 112 | font-size: 1em; 113 | } 114 | .stats span { 115 | border: 1px solid; 116 | padding: .1em .25em; 117 | margin: 0 .1em; 118 | cursor: pointer; 119 | border-color: #999 #ccc #ccc #999; 120 | } 121 | .stats span.hide_run, .stats span.hide_exc, 122 | .stats span.hide_mis, .stats span.hide_par, 123 | .stats span.par.hide_run.hide_par { 124 | border-color: #ccc #999 #999 #ccc; 125 | } 126 | .stats span.par.hide_run { 127 | border-color: #999 #ccc #ccc #999; 128 | } 129 | 130 | .stats span.run { 131 | background: #ddffdd; 132 | } 133 | .stats span.exc { 134 | background: #eeeeee; 135 | } 136 | .stats span.mis { 137 | background: #ffdddd; 138 | } 139 | .stats span.hide_run { 140 | background: #eeffee; 141 | } 142 | .stats span.hide_exc { 143 | background: #f5f5f5; 144 | } 145 | .stats span.hide_mis { 146 | background: #ffeeee; 147 | } 148 | .stats span.par { 149 | background: #ffffaa; 150 | } 151 | .stats span.hide_par { 152 | background: #ffffcc; 153 | } 154 | 155 | /* Help panel */ 156 | #keyboard_icon { 157 | float: right; 158 | margin: 5px; 159 | cursor: pointer; 160 | } 161 | 162 | .help_panel { 163 | position: absolute; 164 | background: #ffffcc; 165 | padding: .5em; 166 | border: 1px solid #883; 167 | display: none; 168 | } 169 | 170 | .indexfile .help_panel { 171 | width: 20em; height: 4em; 172 | } 173 | 174 | .pyfile .help_panel { 175 | width: 16em; height: 8em; 176 | } 177 | 178 | .help_panel .legend { 179 | font-style: italic; 180 | margin-bottom: 1em; 181 | } 182 | 183 | #panel_icon { 184 | float: right; 185 | cursor: pointer; 186 | } 187 | 188 | .keyhelp { 189 | margin: .75em; 190 | } 191 | 192 | .keyhelp .key { 193 | border: 1px solid black; 194 | border-color: #888 #333 #333 #888; 195 | padding: .1em .35em; 196 | font-family: monospace; 197 | font-weight: bold; 198 | background: #eee; 199 | } 200 | 201 | /* Source file styles */ 202 | .linenos p { 203 | text-align: right; 204 | margin: 0; 205 | padding: 0 .5em; 206 | color: #999999; 207 | font-family: verdana, sans-serif; 208 | font-size: .625em; /* 10/16 */ 209 | line-height: 1.6em; /* 16/10 */ 210 | } 211 | .linenos p.highlight { 212 | background: #ffdd00; 213 | } 214 | .linenos p a { 215 | text-decoration: none; 216 | color: #999999; 217 | } 218 | .linenos p a:hover { 219 | text-decoration: underline; 220 | color: #999999; 221 | } 222 | 223 | td.text { 224 | width: 100%; 225 | } 226 | .text p { 227 | margin: 0; 228 | padding: 0 0 0 .5em; 229 | border-left: 2px solid #ffffff; 230 | white-space: pre; 231 | position: relative; 232 | } 233 | 234 | .text p.mis { 235 | background: #ffdddd; 236 | border-left: 2px solid #ff0000; 237 | } 238 | .text p.run, .text p.run.hide_par { 239 | background: #ddffdd; 240 | border-left: 2px solid #00ff00; 241 | } 242 | .text p.exc { 243 | background: #eeeeee; 244 | border-left: 2px solid #808080; 245 | } 246 | .text p.par, .text p.par.hide_run { 247 | background: #ffffaa; 248 | border-left: 2px solid #eeee99; 249 | } 250 | .text p.hide_run, .text p.hide_exc, .text p.hide_mis, .text p.hide_par, 251 | .text p.hide_run.hide_par { 252 | background: inherit; 253 | } 254 | 255 | .text span.annotate { 256 | font-family: georgia; 257 | color: #666; 258 | float: right; 259 | padding-right: .5em; 260 | } 261 | .text p.hide_par span.annotate { 262 | display: none; 263 | } 264 | .text span.annotate.long { 265 | display: none; 266 | } 267 | .text p:hover span.annotate.long { 268 | display: block; 269 | max-width: 50%; 270 | white-space: normal; 271 | float: right; 272 | position: absolute; 273 | top: 1.75em; 274 | right: 1em; 275 | width: 30em; 276 | height: auto; 277 | color: #333; 278 | background: #ffffcc; 279 | border: 1px solid #888; 280 | padding: .25em .5em; 281 | z-index: 999; 282 | border-radius: .2em; 283 | box-shadow: #cccccc .2em .2em .2em; 284 | } 285 | 286 | /* Syntax coloring */ 287 | .text .com { 288 | color: green; 289 | font-style: italic; 290 | line-height: 1px; 291 | } 292 | .text .key { 293 | font-weight: bold; 294 | line-height: 1px; 295 | } 296 | .text .str { 297 | color: #000080; 298 | } 299 | 300 | /* index styles */ 301 | #index td, #index th { 302 | text-align: right; 303 | width: 5em; 304 | padding: .25em .5em; 305 | border-bottom: 1px solid #eee; 306 | } 307 | #index th { 308 | font-style: italic; 309 | color: #333; 310 | border-bottom: 1px solid #ccc; 311 | cursor: pointer; 312 | } 313 | #index th:hover { 314 | background: #eee; 315 | border-bottom: 1px solid #999; 316 | } 317 | #index td.left, #index th.left { 318 | padding-left: 0; 319 | } 320 | #index td.right, #index th.right { 321 | padding-right: 0; 322 | } 323 | #index th.headerSortDown, #index th.headerSortUp { 324 | border-bottom: 1px solid #000; 325 | white-space: nowrap; 326 | background: #eee; 327 | } 328 | #index th.headerSortDown:after { 329 | content: " ↓"; 330 | } 331 | #index th.headerSortUp:after { 332 | content: " ↑"; 333 | } 334 | #index td.name, #index th.name { 335 | text-align: left; 336 | width: auto; 337 | } 338 | #index td.name a { 339 | text-decoration: none; 340 | color: #000; 341 | } 342 | #index tr.total, 343 | #index tr.total_dynamic { 344 | } 345 | #index tr.total td, 346 | #index tr.total_dynamic td { 347 | font-weight: bold; 348 | border-top: 1px solid #ccc; 349 | border-bottom: none; 350 | } 351 | #index tr.file:hover { 352 | background: #eeeeee; 353 | } 354 | #index tr.file:hover td.name { 355 | text-decoration: underline; 356 | color: #000; 357 | } 358 | 359 | /* scroll marker styles */ 360 | #scroll_marker { 361 | position: fixed; 362 | right: 0; 363 | top: 0; 364 | width: 16px; 365 | height: 100%; 366 | background: white; 367 | border-left: 1px solid #eee; 368 | } 369 | 370 | #scroll_marker .marker { 371 | background: #eedddd; 372 | position: absolute; 373 | min-height: 3px; 374 | width: 100%; 375 | } 376 | -------------------------------------------------------------------------------- /cobertura-de-codigo-com-pytest/htmlcov/pode_beber_py.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Coverage for pode_beber.py: 100% 12 | 13 | 14 | 15 | 16 | 17 | 18 | 21 | 22 | 23 | 24 | 42 | 43 |
44 | Hide keyboard shortcuts 45 |

Hot-keys on this page

46 |
47 |

48 | r 49 | m 50 | x 51 | p   toggle line displays 52 |

53 |

54 | j 55 | k   next/prev highlighted chunk 56 |

57 |

58 | 0   (zero) top of page 59 |

60 |

61 | 1   (one) first highlighted chunk 62 |

63 |
64 |
65 | 66 |
67 | 68 | 69 | 109 | 149 | 150 |
70 |

1

71 |

2

72 |

3

73 |

4

74 |

5

75 |

6

76 |

7

77 |

8

78 |

9

79 |

10

80 |

11

81 |

12

82 |

13

83 |

14

84 |

15

85 |

16

86 |

17

87 |

18

88 |

19

89 |

20

90 |

21

91 |

22

92 |

23

93 |

24

94 |

25

95 |

26

96 |

27

97 |

28

98 |

29

99 |

30

100 |

31

101 |

32

102 |

33

103 |

34

104 |

35

105 |

36

106 |

37

107 | 108 |
110 |

#!/usr/bin/env python 

111 |

 

112 |

 

113 |

IDADE_LEGAL = 18 

114 |

SUGESTAO = 'copo d\'água' 

115 |

 

116 |

 

117 |

def verifica_bebida(idade, bebida, alcool, sugestao=SUGESTAO): 

118 |

""" Verifica se a pessoa pode beber álcool de acordo com a idade. Recebe 

119 |

a idade em `idade` como inteiro, nome da bebibda em `bebida` como string, 

120 |

se esta possui álcool em `alcool` como booleano e sugestão em 'sugestao' 

121 |

como string (opcional). Retorna `True` e `bebida` se a idade for maior ou 

122 |

igual a permitida ou `False` e sugestão em caso contrário. """ 

123 |

if idade < IDADE_LEGAL and alcool: # pragma: no cover 

124 |

return False, sugestao 

125 |

else: 

126 |

return True, bebida 

127 |

 

128 |

 

129 |

class TestClass(object): 

130 |

""" Classe de testes para a função Verifica_bebida(). """ 

131 |

 

132 |

def test_maior_pede_cerveja(self): 

133 |

""" Testa se um maior de idade pode pedir uma cerveja. """ 

134 |

assert verifica_bebida(30, 'cerveja', True) == (True, 'cerveja') 

135 |

 

136 |

def test_menor_pede_cerveja(self): 

137 |

""" Testa se um menor de idade pode pedir uma cerveja. """ 

138 |

assert verifica_bebida(15, 'cerveja', True) == (False, SUGESTAO) 

139 |

 

140 |

def test_maior_pede_suco(self): 

141 |

""" Testa se um maior de idade pode pedir um suco. """ 

142 |

assert verifica_bebida(30, 'suco', False) == (True, 'suco') 

143 |

 

144 |

def test_menor_pede_suco(self): 

145 |

""" Testa se um menor de idade pode pedir um suco. """ 

146 |

assert verifica_bebida(15, 'suco', False) == (True, 'suco') 

147 | 148 |
151 |
152 | 153 | 161 | 162 | 163 | 164 | --------------------------------------------------------------------------------