Sunday, February 24, 2008

FSharp - Discovering

I must admit that after Python, It has been difficult for me to find another
language which was as attractive as Python.
I think F# will be this one.


#light

open System

let print x = printfn "%A" x
let sub a b = a - b

let halfway a b =
let dif = b -a
let mid = dif/2
let z = mid + a
z

let y = (fun x y -> x + y) 1 2

let rec fib x =
match x with
| 1 -> 1
| 2 -> 1
| x -> fib (x-1) + fib (x-2)

let UnAnApres =
DateTime.Now + new TimeSpan(365,0,0,0,0)

let print_List l =
List.iter print_string l
print_string "\n"

let shortHand = ["apples"; "pairs"]

shortHand |> printf "%A"

read_line ()

Wednesday, February 6, 2008

Performance Counters - Python

The module win32pdh allows to retrieve performance counters on Windows host
Here is an example published on ASPN.
You will have to use "win32pdhutil.browse" to translate counters names
in your language.


import win32pdh
import win32pdhutil

#Use win32pdh, Kevan Heydon, 2006/06/23
#http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496815

#win32pdhutil.browse()

def uptimeServeur(serveur='Python'):
path = win32pdh.MakeCounterPath( ( serveur, 'Système', None, None, 0, "Temps d'activité système") )
query = win32pdh.OpenQuery()
handle = win32pdh.AddCounter( query, path )
win32pdh.CollectQueryData( query )
seconds = win32pdh.GetFormattedCounterValue( handle, win32pdh.PDH_FMT_LONG | win32pdh.PDH_FMT_NOSCALE )[ 1 ]
return "Serveur : %s - Uptime: %d seconds" %(serveur,seconds )

print uptimeServeur()

Sunday, February 3, 2008

HTA - Python - Sorting Table

This example shows a method to sort a html table in Python within a HTA file
The things to note are:
- Inserting dynamically within a url the name of the list to be display.
- How to sort a list by index

To run HTA files, simply copy this peace of code with the extension '.hta'
and of course Python must be installed (ActiveState Python will do the job)


<html>
<head>
<TITLE>HTML Application Example</TITLE>
<HTA:APPLICATION ID="HTAEx" APPLICATIONNAME="HTAEx" ICON="e.ico" WINDOWSTATE="normal">
</head>

<body onLoad="Initialisation()">

<table><tr><td valign="top"><div id="menu">Menu</td><td><div id="content">contenu</div></td></tr></table>

<script language="Python">

from win32com.client import GetObject
import os
import cPickle as pickle
import base64
import operator

sorteddata = [0]*10

donnee = [('Name','Town','Age'),('Albert','Paris',46),
('Robert','Denver',49),
('Grace','Monaco',18),
('Catherine','Palaiseau',25)]

services = {}


ChaineConnexion = r"WinMgMts:\\%s\%s"

#Menu
menu="""
<p>Menu Principal</p>
<center>
<select name="choices" onChange="SelectOption()">
<option>%s</option>
<option value="service">Service</option>
<option value="process">Process</option>
</select>
</center>
"""%('-'*40)


def getValue(id):
#return document.getElementById(id).value
return document.getElementById(id).getAttribute("value")

def getElt(id):
return document.getElementById(id)

def setValue(divid,data):
elt = document.getElementById(divid)
elt.innerHTML = data

def Pointer():
document.body.style.cursor = "hand"
return

def Default():
document.body.style.cursor = "default"
return


def sortTable(idcol,table):
obj = decodeObj(table)
titre = list(obj[0])
data = obj[1:]
index = titre.index(idcol)
sorteddata[index] = 1 - sorteddata[index]
data.sort(key=operator.itemgetter(index),reverse=sorteddata[index])
data.insert(0,titre)
t = formatTable(data)
setValue('content',t)


def decodeObj(s):
objects = base64.decodestring(s)
return pickle.loads(objects)

def encodeObject(obj):
data = base64.encodestring(pickle.dumps(obj))
return data.__repr__()

def formatTable(data):
tablestr = encodeObject(data)
titre = data[0]
numitem = len(titre)
lnktitre = ["""<span onclick="sortTable('%s',%s)" \
onmouseover='Pointer()' \
onmouseout='Default()'>%s</span>"""%(t,tablestr,t) for t in titre]
table = "<table border='1'>"
table += "<tr>" + ("<td>%s</td>"*numitem)%tuple(lnktitre) + "</tr>"
for item in data[1:] :
table += "<tr>" + ("<td>%s</td>"*numitem)%item + "</tr>"
table += "</table>"
return table

def getAllObjects(serveur = ".", espaceDenom = "root\cimv2", classe = "Win32_Service"):
c = GetObject(ChaineConnexion%(serveur,espaceDenom))
objects = c.ExecQuery(r"select * from %s"%classe)
return objects

def getService():
data = [('Caption','State')]
services = getAllObjects()
for svc in services:
data.append((svc.caption,svc.state))
setValue('content',formatTable (data))

def getProcess():
data = [('Handle','Name','CommandLine')]
process = getAllObjects(classe="Win32_Process")
for proc in process:
data.append((int(proc.Handle),proc.Name,proc.CommandLine))
setValue('content',formatTable (data))

def SelectOption():
services[getValue('choices')]()

services['service'] = getService
services['process'] = getProcess

def Initialisation():
setValue('content',formatTable(donnee))
setValue('menu',menu)
</script>

</body>
</html>

Thursday, January 24, 2008

Sunday, January 20, 2008

ASP.NET - IronPython

It's now possible to use IronPython in Visual Web Developpement Express Edition 2008.
If you are wondering does it worth to switch to IronPython.
Look at this server side part, and compare it with the traditionals languages used

Server Side:

def Page_Load(sender, e):
pass

def onClickButton1(s,e):
color = result.InnerHtml = TextBox1.Text
result.Style.set_Value("background-color:%s;"%color)

def Menu1_MenuItemClick(s,e):
result.Style.set_Value("background-color:red")
choice = Menu1.SelectedValue
result.InnerHtml = choice


Client Part:

<%@ Page Language="IronPython" CodeFile="Default.aspx.py" Inherits="Microsoft.Web.Scripting.UI.ScriptPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="Fichier" Value="Fichier"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="onClickButton1" />
<div id="result" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Friday, January 18, 2008

Boo on .Net

What language choose for .Net : C# VB.NET IronPython ?
Although my language of choice is Python, I must admit
that Boo is very attractive.
It does not have the verbosity of VB.NET or C# and it's syntax
is greatly inspired by Python.
Take a look at this presentation :
http://www.infoq.com/articles/boo-intro

Sunday, December 30, 2007

XUL and Python

You can use Python with XUL with the help of a http server
which execute plain Python Scripts sent by the client.
Like the following :
CPython Server
<?xml version="1।0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="example-window" title="Example 7.2.1"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<script language="javascript">

var wmi=" \n\
import wmi \n\
c = wmi.WMI('Python') \n\
for os in c.Win32_OperatingSystem(): \n\
caption = os.Caption \n\
response = caption \n\
filename = 'foo'"

function WebMethod(url,request,callback)
{
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
alert("Permission UniversalBrowserRead denied.");
}

var http = new XMLHttpRequest();
var mode = request?"POST":"GET";
http.open(mode,url,true);
if(mode=="POST"){http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
http.onreadystatechange=function(){if(http.readyState==4){callback(http.responseText);}};
http.send(request);
}

function CallBack(r)
{
alert(r);
}

</script>
<box id="aBox" width="200">
<button label="GetOsName" oncommand="WebMethod('http://127.0.0.1:9981',wmi,CallBack);"/>
</box>
</window>