SlideShare una empresa de Scribd logo
Taller II   Python Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
Temario ,[object Object]
Python Mysql, PostgreSql
Python Web, Django,
Lenguaje Go
Python Ciencias
http://www.scipy.org/SciPy
Thumbnails con PIL import os, sys, Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + "-thumbnail.jpg" try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, "JPEG") except IOError: print "no se puede con", infile
https://cirl.berkeley.edu/view/Py4Science
Características deseables de un lenguaje para uso en ciencia. ,[object Object]
Fácil de leer.
Fácil de aprender.
Tipo de datos versátiles (alto nivel).
Biblioteca completa (incorporada y disponible externamente).
Suficientemente rápido
Matemática ,[object Object],[object Object]
Funciones algebra lineal
Transformaciones de Fourier
Números aleatorios sofisticados
Herramientas para integrar código C++ y Fortran ,[object Object]
Chaco: 2-Dimensional Plotting
Interfase: GNUPLOT, R, MATLAB.
t200.py import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(111) n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) bincenters = 0.5*(bins[1:]+bins[:-1]) y = mlab.normpdf( bincenters, mu, sigma) l = ax.plot(bincenters, y, 'r--', linewidth=1) ax.set_xlabel('Smarts') ax.set_ylabel('Probability') ax.set_xlim(40, 160) ax.set_ylim(0, 0.03) ax.grid(True) plt.show()
t200.py
from matplotlib import rcParams rcParams['text.usetex']=True rcParams['text.latex.unicode']=True from numpy import arange, cos, pi from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, grid, savefig, show figure(1, figsize=(6,4)) ax = axes([0.1, 0.1, 0.8, 0.7]) t = arange(0.0, 1.0+0.01, 0.01) s = cos(2*2*pi*t)+2 plot(t, s) xlabel(r'extbf{time (s)}') ylabel(ur'extit{Velocity (00B0/sec)}', fontsize=16) title(r"eXis Number $isplaystyleum_{n=1}^nftyrac{-e^{ii}}{2^n}$!", fontsize=16, color='r') grid(True) show() t201.py
t201.py
t202.py #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 1.01, 0.01) s = np.sin(2*2*np.pi*t) plt.fill(t, s*np.exp(-5*t), 'r') plt.grid(True) plt.show()
t202.py
t203.py import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with vertical colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) plt.show()
t203.py
t204.py import numpy as np import matplotlib.pyplot as plt import matplotlib.path as path import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[]) im = ax.imshow(np.random.rand(10,10)) patch = patches.Circle((300,300), radius=100) im.set_clip_path(patch) plt.show()
t204.py
 
Matemática ,[object Object]
http://neopythonic.blogspot.com
Python in the Scientific World * Rapid classification of astronomical time-series data, by Josh Bloom, UCB Astronomy Dept. One of the many tools using Python is GroupThink, which lets random people on the web help classify galaxies (more fun than watching porn :-). * The Hubble Space Telescope team in Baltimore has used Python for 10 years. They showed a tool for removing noise generated by cosmic rays from photos of galaxies. The future James Webb Space Telescope will also be using Python. (Perry Greenfield and Michael Droettboom, of STSCI.) * A $1B commitment by the Indian government to improve education in India includes a project by Prabhu Ramachandran of the Department of Aerospace Engineering at IIT Bombay for Python in Science and Engineering Education in India (see http://fossee.in/).
fperez.org/py4science/2009_guido_ucb/index.html
Python DB
http://sourceforge.net/projects/mysql-python/
01mysql.py #!/usr/local/bin/python #from sets import ImmutableSet import MySQLdb import os, sys db = MySQLdb.connect( host =&quot;localhost&quot;,  user = &quot;root&quot;,  passwd = &quot;123456&quot;,  db = &quot;extdbcat&quot; ) cursor = db.cursor () f = open(&quot;archivo.csv&quot;,&quot;r&quot;) for i in range(1,1050): x = f.readline() f.close() db.close()
http://pymssql.sourceforge.net/
01pymysql.py import pymssql import time import string import unicodedata import codecs conn = pymssql.connect(host='xxx', user='xxx', password='xxx', database='xxxx')  c=conn.cursor() for i in range(1): try: c.execute(&quot;Sentencia&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;&quot; print a r1=c.fetchone()
01pymysqlmejorando.py for i in range(1): try: c.execute(&quot;sql&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;&quot; print a r1=c.fetchone() except pymssql.DatabaseError, err: print str(err) print &quot;Un error en la sesion de la DB &quot; conn.close() break except pymssql.DatabaseError, err: print str(err) print &quot;Fail&quot; time.sleep(0.2) except: print &quot;Fail&quot; time.sleep(0.2)
http://python.projects.postgresql.org/
Postgresql Conn import datetime  connection = psycopg.connect('dbname=COREIS', 'user=roort')  mark = connection.cursor()  st = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')' mark.execute(st)  connection.commit()
Python Web, Django
http://wiki.python.org/moin/WebProgramming
ServidorWeb.py #!/usr/bin/python from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler).serve_forever()
Otro Ejemplo def handle_request(environment, start_response): start_response('200 OK', [('content-type', 'text/html')]) return ['Hello, World!'] if __name__ == '__main__': from wsgiref import simple_server simple_server.make_server('', 8080, handle_request).serve_forever()
00web.py-01 from wsgiref import util from string import Template # Templates wrapper = Template(&quot;&quot;&quot; <html><head><title>$title</title></head><body> $body </body></html> &quot;&quot;&quot;)
00web.py-02 four_oh_four = Template(&quot;&quot;&quot; <html><body> <h1>404-ed!</h1> La URL <i>$url</i> No fue Encontrada. </body></html>&quot;&quot;&quot;)
00web.py-03 pages = { 'index': { 'title': &quot;Hola COREIS&quot;, 'body':  &quot;&quot;&quot;NUESTRA WEB EN PYTHON <a href=&quot;this_page&quot;>COREIS</a>?&quot;&quot;&quot; }, 'this_page': { 'title': &quot;COREIS&quot;, 'body':  &quot;&quot;&quot;Vamos al coreis. <a href=&quot;http://www.coreislima.org/&quot;>COREIS</a>?&quot;&quot;&quot; } }
00web.py-04 def handle_request(environment, start_response): try: fn = util.shift_path_info(environment) if not fn: fn = 'index' response = wrapper.substitute(**pages[fn]) start_response('200 OK', [('content-type', 'text/html')]) except: start_response('404 Not Found', [('content-type', 'text/html')]) response = four_oh_four.substitute(url=util.request_url(environ)) return [response]
00web.py-05 if __name__ == '__main__': from wsgiref import simple_server print(&quot;Starting server on port 8080...&quot;) try: simple_server.make_server('', 8080, handle_request).serve_forever() except KeyboardInterrupt: print(&quot;Ctrl-C Para Salir...&quot;)
email.py-01 import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os
email.py-02 def sendMail(to, subject, text, files=[],server=&quot;localhost&quot;): assert type(to)==list assert type(files)==list fro = &quot;unimauro@gmail.com&quot; msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', &quot;octet-stream&quot;) part.set_payload( open(file,&quot;rb&quot;).read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=&quot;%s&quot;' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string() ) smtp.close() sendMail( [&quot;carlos.cardenas.f@upch.pe&quot;], &quot;hello&quot;,&quot;cheers&quot;, [&quot;usuarios.sql&quot;,&quot;ThekeRS.doc&quot;] )
email02.py-01 import smtplib import mimetypes from email.MIMEText import MIMEText from email.Encoders import encode_base64
email02.py-02 mensaje = MIMEText(&quot;&quot;&quot;Prueba 2 Desde Python&quot;&quot;&quot;) mensaje['From']=&quot;unimauro@gmail.com&quot; mensaje['To']=&quot;carlos.cardenas.f@upch.pe&quot; mensaje['Subject']=&quot;Prueba 2&quot; # Establecemos conexion con el servidor smtp de gmail mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() #mailServer.login(&quot;uio@gmail.com&quot;,&quot;password&quot;) mailServer.login(&quot;unimauro@gmail.com&quot;,&quot;esperanza1504&quot;) # Envio del mensaje mailServer.sendmail(&quot;usuario@gmail.com&quot;, &quot;carlos.cardenas.f@upch.pe&quot;, mensaje.as_string())
 
www.djangoproject.com
 
Models Templates Admin Forms Auth i18n GIS Comments DataBrowse Syndication Sitemaps django-evolution django-registration django-jython django-authopenid django-tagging django-command-extensions google-app-engine-django django-search django-contact-form django-contact-form django-bookmarks django-photologue django-timezones django-profile django-mptt Caching Pinax Satchmo
1. Modelos
# eldemo/elinux/models.py: from django.db import models from datetime import date class Noticia(models.Model):   fecha = models.DateField(   default=date.today)   titulo = models.CharField(max_length=80)   contenido = models.TextField()
class Expositor(models.Model):   nombre = models.CharField(max_length=80,   unique=True)   foto = models.ImageField(   upload_to=&quot;fotos&quot;)   resena = models.TextField(null=True,   blank=True)   invitado = models.BooleanField()
class Charla(models.Model):   titulo = models.CharField(max_length=120,   unique=True)   expositor = models.ForeignKey(Expositor)
¿SQL?
¿SQL? R: Lo genera Django
BEGIN; CREATE TABLE &quot;elinux_noticia&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(80) NOT NULL,   &quot;contenido&quot; text NOT NULL ) ; CREATE TABLE &quot;elinux_expositor&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;nombre&quot; varchar(80) NOT NULL UNIQUE,   &quot;foto&quot; varchar(100) NOT NULL,   &quot;resena&quot; text NULL ) ; CREATE TABLE &quot;elinux_charla&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(120) NOT NULL UNIQUE,   &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ) ; CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;); COMMIT;
# Python: class Charla(models.Model):   titulo = models.CharField(max_length=120,   unique=True)   expositor = models.ForeignKey(Expositor) -- SQL: CREATE TABLE &quot;elinux_charla&quot; (   &quot;id&quot; serial NOT NULL PRIMARY KEY,   &quot;titulo&quot; varchar(120) NOT NULL UNIQUE,   &quot;expositor_id&quot; integer NOT NULL REFERENCES   &quot;elinux_expositor&quot; (&quot;id&quot;)    DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON   &quot;elinux_charla&quot; (&quot;expositor_id&quot;);
Bonus
from django.contrib import admin from elinux.models import Noticia, Expositor,   Charla admin.site.register(Expositor) admin.site.register(Charla) admin.site.register(Noticia)
 
 
 
 
 
 
 
¿Qué es Plone? Sistema de gestión de contenido web Escrito sobre Zope Programado en Python
Características de Plone como CMS ,[object Object]
Distintas formas de presentar el mismo contenido
Editor HTML WYSIWYG
Flujos de trabajo aplicables al contenido
Herramientas de colaboración
Indexado de texto completo de archivos PDF/OO
Instalación de Plone Descargar Plone desde: http://launchpad.net/plone/3.3/3.3/+download/Plone-3.3-UnifiedInstaller.tgz Ejecutar la instalación: $ tar zxfv Plone-3.3-UnifiedInstaller.tgz $ cd Plone-3.3-UnifiedInstaller/ $ ./install.sh standalone Iniciar el servidor: $ cd $HOME/Plone/zinstance $ ./bin/instance fg Acceder a Plone desde el navegador en: http://localhost:8080/Plone
Instalación de Plone  (para desarrollo) Virtualenv PasteScript ZopeSkel zc.buildout
Requerimientos Editar contenido fácilmente Múltiples usuarios Niveles de acceso Galería de fotos Issue tracker Identidad gráfica Puesta en producción Poi Labs Linux+Apache+Zope
http://www.turbogears.org/
http://code.google.com/appengine
introducción a Google App Engine
Entorno de desarrollo que proporciona: ,[object Object]
Base de datos (no relacional)
Escalabilidad y balanceo de carga automático
API para autenticar usuarios
Servidor de correo electrónico

Más contenido relacionado

La actualidad más candente

02 pythonenpocospasosejercicios.ipynb colaboratory
02 pythonenpocospasosejercicios.ipynb   colaboratory02 pythonenpocospasosejercicios.ipynb   colaboratory
02 pythonenpocospasosejercicios.ipynb colaboratory
Lesli Molina Soto
 

La actualidad más candente (10)

De 0 A Python En 40 Minutos
De 0 A Python En 40 MinutosDe 0 A Python En 40 Minutos
De 0 A Python En 40 Minutos
 
Clase1_Python-CTIC
Clase1_Python-CTICClase1_Python-CTIC
Clase1_Python-CTIC
 
Tests en Java con Groovy y Spock
Tests en Java con Groovy y SpockTests en Java con Groovy y Spock
Tests en Java con Groovy y Spock
 
Lecture 37
Lecture 37Lecture 37
Lecture 37
 
The Original Hacker número 8.
The Original Hacker número 8.The Original Hacker número 8.
The Original Hacker número 8.
 
02 pythonenpocospasosejercicios.ipynb colaboratory
02 pythonenpocospasosejercicios.ipynb   colaboratory02 pythonenpocospasosejercicios.ipynb   colaboratory
02 pythonenpocospasosejercicios.ipynb colaboratory
 
Introduccion a python 3
Introduccion a python 3Introduccion a python 3
Introduccion a python 3
 
bibliotecas c++
bibliotecas c++bibliotecas c++
bibliotecas c++
 
PostgreSQL À la Debian
PostgreSQL À la DebianPostgreSQL À la Debian
PostgreSQL À la Debian
 
Introduccion a Python. Clase 1
Introduccion a Python. Clase 1Introduccion a Python. Clase 1
Introduccion a Python. Clase 1
 

Similar a Taller II Coreis Python 13112009

Node.js - Eventos para Todos
Node.js - Eventos para TodosNode.js - Eventos para Todos
Node.js - Eventos para Todos
Mariano Iglesias
 
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
Videoconferencias UTPL
 
Python Tutorial Presentation
Python Tutorial PresentationPython Tutorial Presentation
Python Tutorial Presentation
guestccc92ad
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1
martha leon
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimo
martha leon
 

Similar a Taller II Coreis Python 13112009 (20)

Asegúr@IT II - Seguridad en Web
Asegúr@IT II - Seguridad en WebAsegúr@IT II - Seguridad en Web
Asegúr@IT II - Seguridad en Web
 
Python Multiuso
Python MultiusoPython Multiuso
Python Multiuso
 
Modelo Simulado
Modelo SimuladoModelo Simulado
Modelo Simulado
 
Node.js - Eventos para Todos
Node.js - Eventos para TodosNode.js - Eventos para Todos
Node.js - Eventos para Todos
 
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
UTPL-PROGRAMACIÓN AVANZADA-II-BIMESTRE-(OCTUBRE 2011-FEBRERO 2012)
 
Curso de Django | Django Course
Curso de Django | Django CourseCurso de Django | Django Course
Curso de Django | Django Course
 
Informe minishell
Informe minishellInforme minishell
Informe minishell
 
Python Tutorial Presentation
Python Tutorial PresentationPython Tutorial Presentation
Python Tutorial Presentation
 
Especialista Web J9 Php
Especialista Web J9  PhpEspecialista Web J9  Php
Especialista Web J9 Php
 
Java 7- Java Day Guatemala
Java 7- Java Day GuatemalaJava 7- Java Day Guatemala
Java 7- Java Day Guatemala
 
Introduccion a Python
Introduccion a PythonIntroduccion a Python
Introduccion a Python
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimo
 
REPLs
REPLsREPLs
REPLs
 
Introducción a Python
Introducción a PythonIntroducción a Python
Introducción a Python
 
Codigos de programas
Codigos de programasCodigos de programas
Codigos de programas
 
Codigos de programas
Codigos de programasCodigos de programas
Codigos de programas
 
Hebras En Accion
Hebras En AccionHebras En Accion
Hebras En Accion
 
Creacion de proyecto_en_netbeans
Creacion de proyecto_en_netbeansCreacion de proyecto_en_netbeans
Creacion de proyecto_en_netbeans
 
Sockets
SocketsSockets
Sockets
 

Más de Carlos Cardenas Fernandez

Más de Carlos Cardenas Fernandez (20)

SummitData.pdf
SummitData.pdfSummitData.pdf
SummitData.pdf
 
Data_Science_Machine_Learning_Base.pdf
Data_Science_Machine_Learning_Base.pdfData_Science_Machine_Learning_Base.pdf
Data_Science_Machine_Learning_Base.pdf
 
Inteligencia artificial: Estado del Arte
Inteligencia artificial: Estado del ArteInteligencia artificial: Estado del Arte
Inteligencia artificial: Estado del Arte
 
Inteligencia artificial: Transformando Mercados
Inteligencia artificial: Transformando MercadosInteligencia artificial: Transformando Mercados
Inteligencia artificial: Transformando Mercados
 
Google Summer of Code 2018 :: Envuelvete
Google Summer of Code 2018 :: EnvuelveteGoogle Summer of Code 2018 :: Envuelvete
Google Summer of Code 2018 :: Envuelvete
 
Impacto del software libre en la eduacion
Impacto del software libre en la eduacionImpacto del software libre en la eduacion
Impacto del software libre en la eduacion
 
Sustentacion de Tesis Ingenieria de Usabilidad
Sustentacion de Tesis Ingenieria de UsabilidadSustentacion de Tesis Ingenieria de Usabilidad
Sustentacion de Tesis Ingenieria de Usabilidad
 
St285 U09 II Clase 11/09/2009
St285 U09 II Clase 11/09/2009St285 U09 II Clase 11/09/2009
St285 U09 II Clase 11/09/2009
 
Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01
Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01
Clase de Aplicación de Negocios Electrónicos St295 U09 Ii01
 
Python Tercera Sesion de Clases
Python Tercera Sesion de ClasesPython Tercera Sesion de Clases
Python Tercera Sesion de Clases
 
Python Segunda Sesion de Clases
Python Segunda Sesion de ClasesPython Segunda Sesion de Clases
Python Segunda Sesion de Clases
 
Integración de Pymes
Integración de PymesIntegración de Pymes
Integración de Pymes
 
ST289U2009I Clase29052009
ST289U2009I Clase29052009ST289U2009I Clase29052009
ST289U2009I Clase29052009
 
Portales Con Adsense
Portales Con AdsensePortales Con Adsense
Portales Con Adsense
 
ST289U2009I Clase22052009
ST289U2009I Clase22052009ST289U2009I Clase22052009
ST289U2009I Clase22052009
 
UNET Integrando a las Pymes
UNET Integrando a las PymesUNET Integrando a las Pymes
UNET Integrando a las Pymes
 
GSOC: POSTNUKE
GSOC: POSTNUKEGSOC: POSTNUKE
GSOC: POSTNUKE
 
PLATAFORMA PARA PYMES ASOCIADAS
PLATAFORMA PARA PYMES ASOCIADASPLATAFORMA PARA PYMES ASOCIADAS
PLATAFORMA PARA PYMES ASOCIADAS
 
Sistemas Electricos Y Electronicos 01
Sistemas Electricos Y Electronicos 01Sistemas Electricos Y Electronicos 01
Sistemas Electricos Y Electronicos 01
 
GSoC en la UNI
GSoC en la UNIGSoC en la UNI
GSoC en la UNI
 

Taller II Coreis Python 13112009

  • 1. Taller II Python Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]
  • 2.
  • 8. Thumbnails con PIL import os, sys, Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + &quot;-thumbnail.jpg&quot; try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, &quot;JPEG&quot;) except IOError: print &quot;no se puede con&quot;, infile
  • 10.
  • 13. Tipo de datos versátiles (alto nivel).
  • 14. Biblioteca completa (incorporada y disponible externamente).
  • 16.
  • 20.
  • 23. t200.py import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_subplot(111) n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75) bincenters = 0.5*(bins[1:]+bins[:-1]) y = mlab.normpdf( bincenters, mu, sigma) l = ax.plot(bincenters, y, 'r--', linewidth=1) ax.set_xlabel('Smarts') ax.set_ylabel('Probability') ax.set_xlim(40, 160) ax.set_ylim(0, 0.03) ax.grid(True) plt.show()
  • 25. from matplotlib import rcParams rcParams['text.usetex']=True rcParams['text.latex.unicode']=True from numpy import arange, cos, pi from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, grid, savefig, show figure(1, figsize=(6,4)) ax = axes([0.1, 0.1, 0.8, 0.7]) t = arange(0.0, 1.0+0.01, 0.01) s = cos(2*2*pi*t)+2 plot(t, s) xlabel(r'extbf{time (s)}') ylabel(ur'extit{Velocity (00B0/sec)}', fontsize=16) title(r&quot;eXis Number $isplaystyleum_{n=1}^nftyrac{-e^{ii}}{2^n}$!&quot;, fontsize=16, color='r') grid(True) show() t201.py
  • 27. t202.py #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 1.01, 0.01) s = np.sin(2*2*np.pi*t) plt.fill(t, s*np.exp(-5*t), 'r') plt.grid(True) plt.show()
  • 29. t203.py import matplotlib.pyplot as plt import numpy as np from numpy.random import randn fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with vertical colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['< -1', '0', '> 1']) fig = plt.figure() ax = fig.add_subplot(111) data = np.clip(randn(250, 250), -1, 1) cax = ax.imshow(data, interpolation='nearest') ax.set_title('Gaussian noise with horizontal colorbar') cbar = fig.colorbar(cax, ticks=[-1, 0, 1], orientation='horizontal') cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) plt.show()
  • 31. t204.py import numpy as np import matplotlib.pyplot as plt import matplotlib.path as path import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111, frameon=False, xticks=[], yticks=[]) im = ax.imshow(np.random.rand(10,10)) patch = patches.Circle((300,300), radius=100) im.set_clip_path(patch) plt.show()
  • 33.  
  • 34.
  • 36. Python in the Scientific World * Rapid classification of astronomical time-series data, by Josh Bloom, UCB Astronomy Dept. One of the many tools using Python is GroupThink, which lets random people on the web help classify galaxies (more fun than watching porn :-). * The Hubble Space Telescope team in Baltimore has used Python for 10 years. They showed a tool for removing noise generated by cosmic rays from photos of galaxies. The future James Webb Space Telescope will also be using Python. (Perry Greenfield and Michael Droettboom, of STSCI.) * A $1B commitment by the Indian government to improve education in India includes a project by Prabhu Ramachandran of the Department of Aerospace Engineering at IIT Bombay for Python in Science and Engineering Education in India (see http://fossee.in/).
  • 40. 01mysql.py #!/usr/local/bin/python #from sets import ImmutableSet import MySQLdb import os, sys db = MySQLdb.connect( host =&quot;localhost&quot;, user = &quot;root&quot;, passwd = &quot;123456&quot;, db = &quot;extdbcat&quot; ) cursor = db.cursor () f = open(&quot;archivo.csv&quot;,&quot;r&quot;) for i in range(1,1050): x = f.readline() f.close() db.close()
  • 42. 01pymysql.py import pymssql import time import string import unicodedata import codecs conn = pymssql.connect(host='xxx', user='xxx', password='xxx', database='xxxx') c=conn.cursor() for i in range(1): try: c.execute(&quot;Sentencia&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;&quot; print a r1=c.fetchone()
  • 43. 01pymysqlmejorando.py for i in range(1): try: c.execute(&quot;sql&quot;) result1=c.fetchall() r1 = c.fetchone() while r1: a=r1[0]+&quot; , &quot;+r1[1]+&quot; ,student&quot;+&quot;&quot; print a r1=c.fetchone() except pymssql.DatabaseError, err: print str(err) print &quot;Un error en la sesion de la DB &quot; conn.close() break except pymssql.DatabaseError, err: print str(err) print &quot;Fail&quot; time.sleep(0.2) except: print &quot;Fail&quot; time.sleep(0.2)
  • 45. Postgresql Conn import datetime connection = psycopg.connect('dbname=COREIS', 'user=roort') mark = connection.cursor() st = 'INSERT INTO ' + table + ' (' + columns + ') VALUES (' + values + ')' mark.execute(st) connection.commit()
  • 48. ServidorWeb.py #!/usr/bin/python from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler).serve_forever()
  • 49. Otro Ejemplo def handle_request(environment, start_response): start_response('200 OK', [('content-type', 'text/html')]) return ['Hello, World!'] if __name__ == '__main__': from wsgiref import simple_server simple_server.make_server('', 8080, handle_request).serve_forever()
  • 50. 00web.py-01 from wsgiref import util from string import Template # Templates wrapper = Template(&quot;&quot;&quot; <html><head><title>$title</title></head><body> $body </body></html> &quot;&quot;&quot;)
  • 51. 00web.py-02 four_oh_four = Template(&quot;&quot;&quot; <html><body> <h1>404-ed!</h1> La URL <i>$url</i> No fue Encontrada. </body></html>&quot;&quot;&quot;)
  • 52. 00web.py-03 pages = { 'index': { 'title': &quot;Hola COREIS&quot;, 'body': &quot;&quot;&quot;NUESTRA WEB EN PYTHON <a href=&quot;this_page&quot;>COREIS</a>?&quot;&quot;&quot; }, 'this_page': { 'title': &quot;COREIS&quot;, 'body': &quot;&quot;&quot;Vamos al coreis. <a href=&quot;http://www.coreislima.org/&quot;>COREIS</a>?&quot;&quot;&quot; } }
  • 53. 00web.py-04 def handle_request(environment, start_response): try: fn = util.shift_path_info(environment) if not fn: fn = 'index' response = wrapper.substitute(**pages[fn]) start_response('200 OK', [('content-type', 'text/html')]) except: start_response('404 Not Found', [('content-type', 'text/html')]) response = four_oh_four.substitute(url=util.request_url(environ)) return [response]
  • 54. 00web.py-05 if __name__ == '__main__': from wsgiref import simple_server print(&quot;Starting server on port 8080...&quot;) try: simple_server.make_server('', 8080, handle_request).serve_forever() except KeyboardInterrupt: print(&quot;Ctrl-C Para Salir...&quot;)
  • 55. email.py-01 import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os
  • 56. email.py-02 def sendMail(to, subject, text, files=[],server=&quot;localhost&quot;): assert type(to)==list assert type(files)==list fro = &quot;unimauro@gmail.com&quot; msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', &quot;octet-stream&quot;) part.set_payload( open(file,&quot;rb&quot;).read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=&quot;%s&quot;' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string() ) smtp.close() sendMail( [&quot;carlos.cardenas.f@upch.pe&quot;], &quot;hello&quot;,&quot;cheers&quot;, [&quot;usuarios.sql&quot;,&quot;ThekeRS.doc&quot;] )
  • 57. email02.py-01 import smtplib import mimetypes from email.MIMEText import MIMEText from email.Encoders import encode_base64
  • 58. email02.py-02 mensaje = MIMEText(&quot;&quot;&quot;Prueba 2 Desde Python&quot;&quot;&quot;) mensaje['From']=&quot;unimauro@gmail.com&quot; mensaje['To']=&quot;carlos.cardenas.f@upch.pe&quot; mensaje['Subject']=&quot;Prueba 2&quot; # Establecemos conexion con el servidor smtp de gmail mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() #mailServer.login(&quot;uio@gmail.com&quot;,&quot;password&quot;) mailServer.login(&quot;unimauro@gmail.com&quot;,&quot;esperanza1504&quot;) # Envio del mensaje mailServer.sendmail(&quot;usuario@gmail.com&quot;, &quot;carlos.cardenas.f@upch.pe&quot;, mensaje.as_string())
  • 59.  
  • 61.  
  • 62. Models Templates Admin Forms Auth i18n GIS Comments DataBrowse Syndication Sitemaps django-evolution django-registration django-jython django-authopenid django-tagging django-command-extensions google-app-engine-django django-search django-contact-form django-contact-form django-bookmarks django-photologue django-timezones django-profile django-mptt Caching Pinax Satchmo
  • 64. # eldemo/elinux/models.py: from django.db import models from datetime import date class Noticia(models.Model): fecha = models.DateField( default=date.today) titulo = models.CharField(max_length=80) contenido = models.TextField()
  • 65. class Expositor(models.Model): nombre = models.CharField(max_length=80, unique=True) foto = models.ImageField( upload_to=&quot;fotos&quot;) resena = models.TextField(null=True, blank=True) invitado = models.BooleanField()
  • 66. class Charla(models.Model): titulo = models.CharField(max_length=120, unique=True) expositor = models.ForeignKey(Expositor)
  • 68. ¿SQL? R: Lo genera Django
  • 69. BEGIN; CREATE TABLE &quot;elinux_noticia&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(80) NOT NULL, &quot;contenido&quot; text NOT NULL ) ; CREATE TABLE &quot;elinux_expositor&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;nombre&quot; varchar(80) NOT NULL UNIQUE, &quot;foto&quot; varchar(100) NOT NULL, &quot;resena&quot; text NULL ) ; CREATE TABLE &quot;elinux_charla&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(120) NOT NULL UNIQUE, &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ) ; CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;); COMMIT;
  • 70. # Python: class Charla(models.Model): titulo = models.CharField(max_length=120, unique=True) expositor = models.ForeignKey(Expositor) -- SQL: CREATE TABLE &quot;elinux_charla&quot; ( &quot;id&quot; serial NOT NULL PRIMARY KEY, &quot;titulo&quot; varchar(120) NOT NULL UNIQUE, &quot;expositor_id&quot; integer NOT NULL REFERENCES &quot;elinux_expositor&quot; (&quot;id&quot;) DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX &quot;elinux_charla_expositor_id&quot; ON &quot;elinux_charla&quot; (&quot;expositor_id&quot;);
  • 71. Bonus
  • 72. from django.contrib import admin from elinux.models import Noticia, Expositor, Charla admin.site.register(Expositor) admin.site.register(Charla) admin.site.register(Noticia)
  • 73.  
  • 74.  
  • 75.  
  • 76.  
  • 77.  
  • 78.  
  • 79.  
  • 80. ¿Qué es Plone? Sistema de gestión de contenido web Escrito sobre Zope Programado en Python
  • 81.
  • 82. Distintas formas de presentar el mismo contenido
  • 84. Flujos de trabajo aplicables al contenido
  • 86. Indexado de texto completo de archivos PDF/OO
  • 87. Instalación de Plone Descargar Plone desde: http://launchpad.net/plone/3.3/3.3/+download/Plone-3.3-UnifiedInstaller.tgz Ejecutar la instalación: $ tar zxfv Plone-3.3-UnifiedInstaller.tgz $ cd Plone-3.3-UnifiedInstaller/ $ ./install.sh standalone Iniciar el servidor: $ cd $HOME/Plone/zinstance $ ./bin/instance fg Acceder a Plone desde el navegador en: http://localhost:8080/Plone
  • 88. Instalación de Plone (para desarrollo) Virtualenv PasteScript ZopeSkel zc.buildout
  • 89. Requerimientos Editar contenido fácilmente Múltiples usuarios Niveles de acceso Galería de fotos Issue tracker Identidad gráfica Puesta en producción Poi Labs Linux+Apache+Zope
  • 93.
  • 94. Base de datos (no relacional)
  • 95. Escalabilidad y balanceo de carga automático
  • 97. Servidor de correo electrónico
  • 100. Es gratis: 500MB en disco y 5 millones de páginas vistas
  • 101. 1. Registrar una cuenta http://appengine.google.com/
  • 102. 2. Descargar el SDK http://code.google.com/intl/es/appengine/downloads.html
  • 103. Creamos el archivo helloworld.py en dicho directorio con el contenido: print 'Content-Type: text/plain' print '' print 'Hola Mundo!' Editamos el archivo de configuración app.yaml: application: helloworld version: 1 runtime: python api_version: 1 handlers: - url: /.* script: helloworld.py
  • 104. Para comprobar que funciona, arrancamos el servidor, bien con la interfaz gráfica o en la terminal con: dev_appserver.py helloworld Y accedemos a http://localhost:8080 donde nos debería aparecer “Hola Mundo!” en el navegador.
  • 105. Permite crear aplicaciones basadas en CGI de forma fácil y rápida. Editamos el archivo helloworld.py: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('Hola Mundo con webapp!') application = webapp.WSGIApplication( [('/', MainPage)], debug=True) def main(): run_wsgi_app(application) if __name__ == &quot;__main__&quot;: main()
  • 106. Entramos en http://appengine.google.com y creamos una aplicación (OJO! Luego no se puede borrar). Editamos el archivo app.yaml y cambiamos el nombre de application por el que hemos usado anteriormente. Subimos la aplicación: (nos pedirá usuario y contraseña de nuestra cuenta de Google) appcfg.py update helloworld Podemos comprobar si ha funcionado entrando en http://<tu_aplicacion>.appspot.com
  • 107. 11. Más Ejemplos Ejemplos didácticos http://code.google.com/p/google-app-engine-samples/ Ejemplos funcionando http://flickrsearchr.appspot.com/ http://www.cafesurvey.com/ http://www.congregar.com/ http://www.urlmetrix.com/ http://zchat.appspot.com http://www.jumbra.com/
  • 110. Lenguaje para Linux y MacOSX. PARTE I Configuración e Instalación 1. Instalar: sudo apt-get install mercurial sudo apt-get install bison gcc libc6-dev ed make 2. Configurar Variables de Entorno: export GOARCH=386 export GOROOT=/home/administrador/hg/ export GOBIN=/home/administrador/hg/bin 3. Verificar Variables de Entorno env | grep ^GO
  • 111. 4. Crear Carpeta Bin si es se quiere instalar en otra carpeta mkdir bin 5. Agregar la Variable $GOBIN al PATH de Linux export PATH+=:$GOBIN 6. Verificar: echo $PATH 7. Ingresando a la Carpeta de los Fuentes: cd $GOROOT/src 8. Iniciar la Compilación: ./all.bash Verificar Que todo es OK
  • 112. PARTE II 1. vim Hola_Coreis_GO.go package main import &quot;fmt&quot; func main() { fmt.Printf(&quot;Hola Somos Coreis, La Singularidad de las Ciencias&quot;) }
  • 113. 2. Compilación /home/administrador/bin/8g Hola_Coreis_GO.go /home/administrador/bin/8l Hola_Coreis_GO.8 3. Ejecución: ./8.out
  • 114. package main import &quot;os&quot; import &quot;flag&quot; var nFlag = flag.Bool(&quot;n&quot;, false, `no `) func main() { ! flag.Parse(); ! s := &quot;&quot;; ! for i := 0; i < flag.NArg(); i++ { ! ! if i > 0 { s += &quot; &quot; } ! ! s += flag.Arg(i) ! } ! if !*nFlag { s += &quot;&quot; } ! os.Stdout.WriteString(s); }
  • 117.  
  • 118.  
  • 123. Carlos Mauro Cárdenas Fernández http://unimauro.blogspot.com http://www.twitter.com/unimauro [email_address]

Notas del editor

  1. Por ejemplo, dos autos del mismo modelo, color, motor, salidos de la misma línea de producción el mismo día no dejan de ser dos autos diferentes, por más que su conjunto de atributos y sus valores sean iguales. La única posibilidad de que dos objetos sean iguales es que sean el mismo objeto.
  2. http://www.flickr.com/photos/ryanricketts/2295726918/sizes/o/
  3. http://www.flickr.com/photos/twatson/2854156629/sizes/l/