Como tomar decisões
Agora pouco, no IM:
trajber: vou pedir ajuda ao meu querido PC
trajber: mauro@trajber:~$ python
Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
[GCC 4.3.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import random
>>> print random.randint(0,1)
trajber: 0 = ignorar
trajber: 1 = comer
trajber: ok ?
trajber: 0
>>>
trajber: foi justo…
Outro também fez algo parecido: http://twitter.com/igorrs/status/896944758
Sem comentários »Book Meme
Time is always critical because somebody might beat you to the punch
Founders at Work, Jessica Livingston
- Grab the nearest book.
- Open it to page 56.
- Find the fifth sentence.
- Post the text of the sentence in your journal along with these # instructions.
- Don’t dig for your favorite book, the cool book, or the intellectual one: pick the CLOSEST.
Javascript (Ajax) e HTML em Lisp
Para testar algumas coisas refiz hoje o código do post Common Lisp e Ajax. Desta vez estou usando o patch para o HT-AJAX com suporte e jQuery. Além disso, para gerar código JavaScript uso Parenscript. Assim todo HTML e JS é produzido por s-exps:
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *dependencies*
‘(:asdf :hunchentoot :ht-ajax :cl-who :parenscript))
(map nil ‘require *dependencies*))
(defpackage :ajax-test
(:use :common-lisp :hunchentoot :ht-ajax :cl-who :parenscript))
(in-package :ajax-test)
(defparameter *local-dir* “/Users/lucindo/Documents/Lisp/web/3rdparty/”)
(defparameter *ajax-handler-url* “/ajax”)
(defparameter *ajax-processor*
(make-ajax-processor :type :jquery
:server-uri *ajax-handler-url*
:js-file-uris “/static/jquery.js”))
(defun testfunc (command)
(prin1-to-string (handler-case (eval (read-from-string command nil))
(error (c) (format nil “~a” c)))))
(defun js ()
(ps
(defun command_clicked ()
(let ((command (document.get-element-by-id “command”)))
(with-slots (value) command
(ajax_testfunc_set_element “result” value))))))
(defun main-page ()
(with-html-output-to-string
(*standard-output* nil :prologue t)
(:html
(:head
(:script :type “text/javascript” :src “/js”)
(:title “AJAX test”)
(fmt “~a” (generate-prologue *ajax-processor*)))
(:body
(:h1 “ajax test”)
(:table :width “50%”
(:tr
(:td :colspan “2″
(:span :id “result”
(:i “no results yet”))))
(:tr
(:td :width “70%”
(:input :type “text”
:size “70″
:name “command”
:id “command”))
(:td (:input :type “button”
:value “eval”
:onclick (ps-inline (command_clicked))))))))))
(eval-when (:load-toplevel :execute)
(export-func *ajax-processor* ‘testfunc :method :post)
(setf *dispatch-table*
(list ‘dispatch-easy-handlers
(create-folder-dispatcher-and-handler “/static/”
*local-dir* “text/plain”)
(create-prefix-dispatcher *ajax-handler-url*
(get-handler *ajax-processor*))
(create-prefix-dispatcher “/js” ‘js)
(create-prefix-dispatcher “/” ‘main-page))))
(defparameter *webserver* nil)
(defun start-web (&optional (port 4242))
(setf *webserver* (start-server :port port)))
(defun stop-web ()
(stop-server *webserver*))
Download: ajax2.lisp
1 comentário »Ruby sucks: parte 42
Há algum tempo eu desisti de Ruby. Como linguagem de programação tem coisas muito legais, mas ainda é muito imatura (apesar da idade). Poderia mostrar vários exemplos de coisas estranhas em Ruby, mas hoje vai a causa de um bug que me mostraram.
Veja se o defined? não funciona de maneira não intuitiva:
lucindo@marvin:~$ irb irb(main):001:0> defined?(cu) => nil irb(main):002:0> if false irb(main):003:1> cu = "ruby" irb(main):004:1> end => nil irb(main):005:0> defined?(cu) => "local-variable" irb(main):006:0> if defined?(cu) irb(main):007:1> puts "ruby cu" irb(main):008:1> end ruby cu => nil irb(main):009:0>
Imagina se você usa isso em algo como configuração…
5 comentários »ACE_Task-like em Python
Nos últmos dias me reanimei a voltar a postar nesse blog.
Estou tentando mudar para Python como a minha principal linguagem de script, mas ainda preciso aprender a programar direito nessa linguagem. Enquanto isso não acontece, eu fico replicando código de outros lugares, como a cópia de pobre da ACE_Task abaixo:
import threading, Queue, signal
class Task(object):
def __init__(self):
self.queue = Queue.Queue(0)
def __worker(self):
while True:
item = self.queue.get()
self.process(item)
self.queue.task_done()
def __start(self):
thread = threading.Thread(target=self.__worker)
thread.setDaemon(True)
thread.start()
def activate(self, threads):
for thread in xrange(threads):
self.__start()
signal.signal(signal.SIGINT, signal.SIG_DFL)
def put(self, item):
self.queue.put(item)
def wait(self):
self.queue.join()
def process(self, item):
pass
class task(Task):
def __init__(self, func):
Task.__init__(self)
self.process = func
A única coisa pytônica do código é o decorator do final.
Bom, um exemplo de uso: digamos que você é um spammer e quer mandar vários emails. Você tem um arquivo em que cada linha tem as seguintes informações: servidor; email; subject; mensagem. Tudo separado por ponto e vírgula.
Usando o decorator acima o código ficaria mais ou menos assim (usando 100 threads):
from __future__ import with_statement
from task import task
import smtplib, sys
@task
def send_spam(item):
server, toaddr, subject, msg = item.strip().split(‘;’)
fromaddr = ’spammer@evil.org’
message = (“From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s”
% (fromaddr, toaddr, subject, msg))
try:
smtp = smtplib.SMTP(server)
smtp.sendmail(fromaddr, toaddr, message)
except Exception:
pass
def process_file(filename):
send_spam.activate(100)
with open(filename) as file:
map(lambda line: send_spam.put(line), file.readlines())
send_spam.wait()
if __name__ == ‘__main__’:
process_file(sys.argv[1])
Coloquei esse exemplo porque não tinha um melhor… é apenas um exemplo, não um programa de verdade, ok?
Download: task.py
To do: reescrever em Python 2.6 usando Multiprocessos
2 comentários »Frase do dia
Só porque esse blog está muito parado:
Eight years to do TeX? How smart can he be? He should have used Lisp.
Kenny Tilton, sobre Donald Knuth
Sem comentários »HT-AJAX e jQuery
HT-AJAX (documentação aqui) é uma extenção do Hunchentoot que permite exportar suas funções lisp de modo que elas podem ser acessadas via JavaScript, usando AJAX. Um pequeno exemplo de uso dessa biblioteca está nesse post.
HT-AJAX suporta vários AJAX processors, como Prototype e Dojo, mas não jQuery. Então fiz um pequeno patch adicionando suporte a jQuery.
Download: ht-ajax_0.0.7-jquery.patch
Aplicando o patch (SBCL):
$ cd ~/.sbcl/site/ht-ajax_0.0.7 $ wget http://lucindo.com.br/lisp/ht-ajax_0.0.7-jquery.patch $ cat ht-ajax_0.0.7-jquery.patch | patch -p0 $ sbcl * (require :asdf) * (asdf:oos 'asdf:compile-op :ht-ajax)Sem comentários »
About State
State: you’re doing it wrong
I’m completely convinced that mutable objects and the whole approach that is sort of implied by the design of Java, C#, Python, all the languages that followed along this path, is very much the wrong way to do most things… it is ok to do somethings, but it’s the wrong way to do most things.
Mutable objects are the new spaghetti code, and by that I mean that you eventually, with mutable objects, create an intractable mess, and encapsulation does not get rid off that, encapsulation just means: well, I’m in charge of this mess. But the real mess comes from this network you create of objects that can change, and your inability to look at the state of a system and understand how you got there, how to get there to test it next time… so it’s hard to understand the program… it’s very hard to test it. I think that’s interesting in telling all the emphasis on test driven design. I think people are driven to this because they know their systems are completely intractable…
Rich Hickey - Screencast: Clojure Concurrency (”transcrição” do minuto 21 ao 23)