[Tutor] How to open IE7 to a certain URL?

2008-02-29 Thread János Juhász
  I've got this so far:
 
  #!/usr/bin/env python
  #coding=utf-8
  import time
  b = '20:00:00'
  while True:
   a = time.strftime('%H:%M:%S')
   time.sleep(0.5)
   if a == b:
   print TIME!
   break
 

It needn't to make this comparison in every 0.5 seconds.
Calculate how long to sleep and ask that from the pc.


import time
b = '20:00:00'

(bhour, bmin, bsec) = b.split(':')
bsec = int(bsec) + int(bmin)*60 + int(bhour)*360

while True:
act = time.localtime()
actsec = act.tm_sec + act.tm_min*60 + act.tm_hour*360
wait = bsec - actsec
if wait  0:
wait += 360*24 # it will be tomorrow
time.sleep(wait)
print 'I am doing!'
break


Regards,

  Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to convert ogg to MP3

2008-01-03 Thread János Juhász
 goldgod a [EMAIL PROTECTED] wrote in

 I would like to convert ogg files to mp3 files. how can I do
  that.
  Is there any inbuilt package.
 
 I think Lame can do that.
 You would need to access Lame via its command line (using the
 subprocess module?) or maybe someone has a python library
 to use the lame library/DLL directly.

Pymedia promises to do that. (http://pymedia.org/)
There is a sample script about it called recode_audio.py,
but it chrashed my python interpreter on xp, when I tried to convert from 
ogg to mp3.


Best Regards,
Janos___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Output of list

2007-12-23 Thread János Juhász
Dear Emil,

 I want to be capable of converting a string into a list where all 
 the items, in  the list, have a fixed length not equal to 1 e.g i 
 have k = 'abcdefgh' and I want the fixed length for all the the 
 items to be 2 then the list would look like ['ab', 'cd', 'ef, 'gh'].
 How do i do this?

 
 - Emil

It is nice place to use a generator:

def pairs(sliceit):
streamlist = list(sliceit)
streamlist.reverse()
while streamlist:
pair = streamlist.pop() 
try:pair += streamlist.pop()
except: pass
yield pair

## Probably it is easier to understand
def pairs2(sliceit):
try:
while sliceit:
yield sliceit[:2]
sliceit = sliceit[2:]
except: # oops, it was odd length
yield sliceit


print '_'.join(e for e in pairs('abcd'))
print '_'.join(e for e in pairs('abcde'))
print '_'.join(e for e in pairs2('abcd'))
print '_'.join(e for e in pairs2('abcde'))


Best Regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Output of list

2007-12-23 Thread János Juhász
Dear Marty,


... Or, by extending Alan's solution ...

def splitStringByN(s, n):
for m in range(0, len(s), n):
yield s[m:m+n]

k = 'abcdefghi'
list(splitStringByN(k, 2))

It seems to be the most readable solution for me.


As it turns out, this is similar to an ASPN Cookbook recipe contributed
by Dmitry Vasiliev:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069

HTH,
Marty

Thanks for the link.


Best regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] The name of the module

2007-10-17 Thread János Juhász
Dear Tutors,

there was a thread some weeks ago about
how can we find out 
what is the name of the current module, 
where the function was loaded from,
where the function running from or so, 
with some magic.

I can't find it in the archive.

May someone help me with some reference about it ?

Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] using **kwargs in __init__() as attributes

2007-10-01 Thread János Juhász
Dear Tutors,

I would like to make a new class instance, where
the intance attributes coming from the kwargs hash.

class ADUser:
def __init__(self, **kwargs):
for key in kwargs.keys():
self.key = kwargs[k]

a = ADUser(name='papa')


It isn't working :(



Yours sincerely,
__
Janos Juhasz

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OO triangulation with attacment

2007-09-20 Thread János Juhász
Dear Tutors,

I made an OO style triangulation based on an old C progam I made about 10 
years ago.
This makes Delaunay triangualtion over a point cloud in 2D. 
http://en.wikipedia.org/wiki/Delaunay_triangulation

The sample is working finally.
First time I made the triangulation with recursion, but I reached the 
recursion limit very shortly.
So I changed the recursion to a queue.

I am interested about your opinions about the OO style I made in it.
It hasn't got too much comments, but probably readable.



I hope you can test the code easily.
I think it has got some interesting programing solutions.



Yours sincerely,
__
János Juhász


triangle.py 
Description: Binary data
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OO triangulation

2007-09-19 Thread János Juhász
  / \ 
d1  /
Ta2 = a2.NextPoint(B)   ##\ /  \  
/
Td1 = d1.NextPoint(C)   ##  Td1Td1

self.points = [A, C, B];t2.points = [D, B, C]
self.neighbours = [t2, a2, a1]; t2.neighbours = [self, d1, d2]

d1.SetTriangle(Td1 ,t2);a2.SetTriangle(Ta2, self)
 
def NextPoint(self, p):
return self.points[(self.points.index(p)+1)%3]

def PrevPoint(self, p):
return self.points[(self.points.index(p)+2)%3]

def BottomTriangle(self, p):
return self.neighbours[self.points.index(p)]
 
def SetTriangle(self, p, tri):
self.neighbours[self.points.index(p)] = tri

import wx

class DrawingFrame(wx.Frame):
def __init__(self, parent, id, title, fileName=None):
wx.Frame.__init__(self, parent, id, title, style = 
wx.DEFAULT_FRAME_STYLE | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE)
self.Bind(wx.EVT_PAINT, self.onPaintEvent)
self.SetSizeHints(minW=250, minH=200)
self.SetSize(wx.Size(450, 450))
self.SetBackgroundColour(wx.WHITE)
self.CreateStatusBar()

menu = wx.Menu()
retri = menu.Append(-1, 100 new points, 100 new points)
self.Bind(wx.EVT_MENU, self.Retriangulate100, retri)
retri = menu.Append(-1, 1000 new points, 1000 new points)
self.Bind(wx.EVT_MENU, self.Retriangulate1000, retri)
retri = menu.Append(-1, 1 new points, 1 new points)
self.Bind(wx.EVT_MENU, self.Retriangulate1, retri)
menuBar = wx.MenuBar()
menuBar.Append(menu, Retriangulate)
self.SetMenuBar(menuBar)
self.Show()

def Retriangulate100(self, evt):
triang.NewPointSet(100)
start = time.clock()
triang.Triangulate()
stop = time.clock()
self.Refresh()
st = 'Triangulating 100 points takes %.2f seconds' % (stop-start)
self.SetStatusText(st)

def Retriangulate1000(self, evt):
triang.NewPointSet(1000)
start = time.clock()
triang.Triangulate()
stop = time.clock()
self.Refresh()
st = 'Triangulating 1000 points takes %.2f seconds' % (stop-start)
self.SetStatusText(st)

def Retriangulate1(self, evt):
triang.NewPointSet(1)
start = time.clock()
triang.Triangulate()
stop = time.clock()
self.Refresh()
st = 'Triangulating 1 points takes %.2f seconds' % 
(stop-start)
self.SetStatusText(st)

def onPaintEvent(self, event):
dc = wx.PaintDC(self)
dc.BeginDrawing()
for tri in triang.triangles:
if None in tri.points: continue
dc.DrawPolygon(tri.points)
cx, cy = (0,0)
for p in tri.points:
cx += p[0]/3
cy += p[1]/3
r = ((p[0]-cx)**2 + (p[1]-cy)**2)**0.5
#dc.DrawCircle(cx, cy, 2)

dc.EndDrawing()

class App(wx.App):
def OnInit(self):
frame = DrawingFrame(None, -1, Triangulation)
self.SetTopWindow(frame)
frame.Show()
return 1

if __name__ == '__main__':
import random
import time
triang = Triangulation()
triang.NewPointSet(1000)
triang.Triangulate()

app = App(0)
app.MainLoop()
##






Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python and wmi interface

2007-09-19 Thread János Juhász
Dear sacha,

can anyone point me in the direction of any python docs or tutorials 
of interacting with the windows WMI interface ?

Scriptomatic 2.0 from Microsoft seems to be good for pythonists.

https://www.microsoft.com/downloads/details.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178DisplayLang=en

Yours sincerely,
__
János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unicode question

2007-09-12 Thread János Juhász
Dear Kent,

thanks for your respond.
It is clear now.

 As a mnemonic I think of Unicode as pure unencoded data. (This is *not*
 accurate, it is a memory aid!) Then it's easy to remember that decode()
 removes encoding == convert to Unicode, encode() adds encoding ==
 convert from Unicode.

So I had to convert cp852 ascii file into unicode, that can be made with 
page.decode('cp852')

There was another problem also about, o with double acute and O with 
double acute,
as they were missed from the font files.


It works well now.


from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import pagesizes
from reportlab.lib.units import cm

PAGE_HEIGHT=defaultPageSize[1]
import copy

styles = getSampleStyleSheet()
InvStyle = copy.deepcopy(styles[Normal])
InvStyle.fontSize = 8
InvStyle.leading = 9
InvStyle.fontName = 'Courier'
InvLineNum = 92

im = Image(bimbambumm.bmp, width=100, height=35)
im.hAlign = 'RIGHT'


def MakePdfInvoice(InvoiceNum, pages):
PdfInv = []
for page in pages:
PdfInv.append(im)
PdfInv.append(Preformatted(page, InvStyle))
PdfInv.append(PageBreak())
PdfInv = PdfInv[:-1]
 
doc = SimpleDocTemplate(InvoiceNum)
doc.topMargin = 1*cm
doc.bottomMargin = 0
doc.leftMargin = 0
doc.rightMArgin = 0
doc.build(PdfInv)

def BreakIntoPages(content):
while len(content)  InvLineNum:
page = content[:InvLineNum]
content = content[InvLineNum:]
yield page
else:
yield content


if __name__ == '__main__':
content = open('invoice01_0707.txt').readlines()
content = [line.replace('\x8a','\x99').replace('\x8b','\x94') for line 
in content]
pages = []
for page in BreakIntoPages(content):
page = ''.join(page)
pages.append(page.decode('cp852'))
MakePdfInvoice('test.pdf', pages)






Kent Johnson [EMAIL PROTECTED] wrote on 2007.09.11 15:49:24:

 János Juhász wrote:
  Dear All,
 
  I would like to convert my DOS txt file into pdf with reportlab.
  The file can be seen correctly in Central European (DOS) encoding in
  Explorer.
 
  My winxp uses cp852 as default codepage.
 
  When I open the txt file in notepad and set OEM/DOS script for 
terminal
  fonts, it shows the file correctly.
 
  I tried to convert the file with the next way:
 

 Use decode() here, not encode().
 decode() goes towards Unicode
 encode() goes away from Unicode

 As a mnemonic I think of Unicode as pure unencoded data. (This is *not*
 accurate, it is a memory aid!) Then it's easy to remember that decode()
 removes encoding == convert to Unicode, encode() adds encoding ==
 convert from Unicode.

  MakePdfInvoice('test.pdf', page)
 
  But it raised exception:
  ordinal not in range(128)

 When you call encode on a string (instead of a unicode object) the
 string is first decoded to Unicode using ascii encoding. This usually 
fails.

 Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Unicode question

2007-09-11 Thread János Juhász
Dear All,

I would like to convert my DOS txt file into pdf with reportlab.
The file can be seen correctly in Central European (DOS) encoding in 
Explorer.

My winxp uses cp852 as default codepage.

When I open the txt file in notepad and set OEM/DOS script for terminal 
fonts, it shows the file correctly.

I tried to convert the file with the next way:

from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]

styles = getSampleStyleSheet()

def MakePdfInvoice(InvoiceNum, page):
style = styles[Normal]
PdfInv = [Spacer(0,0)]
PdfInv.append(Preformatted(page, styles['Normal']))
doc = SimpleDocTemplate(InvoiceNum)
doc.build(PdfInv)

if __name__ == '__main__':
content = open('invoice01_0707.txt').readlines()
page = ''.join(content[:92])
page = unicode(page, 'Latin-1')
MakePdfInvoice('test.pdf', page)

But it made funny chars somewhere.

I tried it so eighter

if __name__ == '__main__':
content = open('invoice01_0707.txt').readlines()
page = ''.join(content[:92])
page = page.encode('cp852')
MakePdfInvoice('test.pdf', page)

But it raised exception:
debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File 
C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py, line 
60, in run
_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File 
C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py, line 
631, in run
exec cmd in globals, locals
  File D:\devel\reportlab\MakePdfInvoice.py, line 18, in ?
page = page.encode('cp852')
  File c:\Python24\lib\encodings\cp852.py, line 18, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 112: 
ordinal not in range(128)
 

May someone point me where I made it wrong ?

Best regards,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Importing Excel sheet data

2007-09-06 Thread János Juhász
Dear Saradhi,

I am using COM on Win32 for this, 
based on the sample of Mark Hammond  Andy Robinson 
in the Programing Python on Win32 book.
That is a fairly simple way to do that.

The code itself can be downloaded from 
http://examples.oreilly.com/pythonwin32/ppw32_samples.zip

You can find some information about it googling for EasyExcel.

The book itself is an essential to work on win32 with python.
# My personal favorite chapters are the ones about double-entry 
bookkeeping :)

 Date: Wed, 5 Sep 2007 21:07:41 -0500
 From: saradhi dinavahi [EMAIL PROTECTED]

 I am new to the Python Programming. I want to Import Excel sheet data 
using
 Python. Can any one please provide me the code and explain the basic 
steps
 and method of executing the code.


Janos Juhasz___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Triangle structure for triangulation

2007-08-30 Thread János Juhász
Dear All,


I have written a Delaunay triangulation 10 years ago 
in C based on triangle structure.
It was 400 lines, so it seems to be a fine task to turn into python.


My problem is the translation of the C structure and the OO thinking.
I tried to draft it so.


/*
The triangle, its neighbours,
sides and rotations.
 
   0
 VTOP
/\ 
   / t  r \
  LEFT/ oo \RIGHT 1
 / r  t \
/   act\
1 VLEFTVRIGHT 2
BOTTOM
   0
*/

typedef struct{
 TRIINDEXneighbour[3];  // triangles: bottom, right, left
 POINTINDEX  vertex[3]; // vertex: top, left, right
 float   height;// elevation
} TRIANGLE;


Each triangle has three vertices and three neighbours.
To calculate the elvation on the triangulation at a given point,
it is important to find the coresponding triangle as fast as possible,
so the triangles had directions. But it was important in the update 
process too.
So I had an array with the triangles, but the neighbours were
directed triangles not simple triangle (TRIINDEX).

There were C macros to get the neighbours of the triangles.
To get the left triangle tleft = LEFT(t), tright = RIGHT(t), tbottom = 
BOTTOM(t)

ROT(t) was the same triangle as t, but rotated ccw.
so t = ROT(ROT(ROT(t)))
TOR(t) was the same triangle as t, but rotated cw.
t = TOR(TOR(TOR(t)))

In C, I have used 
typedef unsigned intTRIINDEX;
to identify a triangle, where the last two bites were used to handle the 
directions.

## I can translate it into python in this way
class Triangle:
def __init__(self, points, neighbours):
self.points = points
self.neighbours = neighbours

  def TOR(self, direction):
return (self, (direction+1)%3)

  def ROT(self, direction):
return (self, (direction+2)%3)

  def RIGHT(self, direction):
return (self.neighbours[(direction+2)%3])
 


I would ask your opinions to encapsulate a triangle into a directed 
triangle.
I made my first trial on the way to keep a directed triangle as a tuple 
(triangle, direction)
and register it in that way.
I would like to use directed triangles, but wouldn't like to use too much 
memory.




Yours sincerely,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Triangle structure for triangulation

2007-08-30 Thread János Juhász
Dear Allan,

thanks for your coments.

  ## I can translate it into python in this way
  class Triangle:
 def __init__(self, points, neighbours):
 self.points = points
 self.neighbours = neighbours
 
   def TOR(self, direction):
 return (self, (direction+1)%3)
 
   def ROT(self, direction):
 return (self, (direction+2)%3)
 
   def RIGHT(self, direction):
 return (self.neighbours[(direction+2)%3])
 
  I would ask your opinions to encapsulate a triangle into a directed
  triangle.
 
 I'm not totally sure what you are looking for but my first
 guess would be to add a direction argument to the init
 and store it as an attribute. But it sounds like you need
 to add some methods too. What do you do with these
 triangles? From your descriptionI'd expect to see some
 methods taking other triangles as arguments?

The triangulation would be used for surface modelling.
The most important function is CalcZ(point(x, y)), that interpolates the
elevation on the surface of a triangle.
For this interpolation I have to find the corresponding triangle of the 
point,
that can be made the fastest by walking from triangle to triangle.
This is the first reason I need the neighbours.

I also need to extend and update the triangulation, when a new point 
inserted into it.

 For example you store the points but never use them.
 Attributes in a class shjould be thee to support the metjods.
 If the atrributes are not used by any method that implies
 that they are not needed or that you are accessing them
 from some function outside the class, which is probably
 an indication of bad OO design.

I feel that, the best would be to strore 3 separate triangles for A,B,C 
points,

Triangulation.Append(Triangle(A,B,C))
Triangulation.Append(Triangle(B,C,A))
Triangulation.Append(Triangle(C,A,B))
And register the topological relations after it. It could be OO, and 
simple.


As I wrote, I made it in C with structures, so it wasn't OO, but fast.
I can translate a C iteration over C structures into python,
to iterate over class objects, and usually I don't miss the pointers.
Except now, when the algorithm based strongly on pointers and indeces :(


Yours sincerely,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] iterate list items as lvalue

2007-08-22 Thread János Juhász
Dear All,

I would like to thanks for your responds.


Ricardo Aráoz wrote:
  Kent Johnson wrote:
   Dave Kuhlman wrote:
   Consider the following:
  
array = [1,2,3,4,5]
array2 = array
array = [i * 2 for i in array]
array
   [2, 4, 6, 8, 10]
array2
   [1, 2, 3, 4, 5]
  
   So, did you want array2 to change, or not?
  
   Here is a solution that changes the object that both array and
   array2 refer to:
  
array = [1, 2, 3, 4, 5]
array2 = array
for idx, item in enumerate(array):
   array[idx] = item * 2
array
   [2, 4, 6, 8, 10]
array2
   [2, 4, 6, 8, 10]
  
   Basically, this modifies the list in place, rather than making a
   new list from the old one.
   
   Another way to do this is to assign to a slice of array:
   
   array[:] = [ item*2 for item in array ]
   
   Kent
  Thanks, hadn't really thought about having a copy of array (guess I'm
  too much of a n00b). Really simple and elegant way of solving it though.

I have played the way Kent showed.

 array = [1, 2, 3, 4, 5]
 array[2] = [item+5 for item in array]
 array
[1, 2, [6, 7, 8, 9, 10], 4, 5]

 array = [1, 2, 3, 4, 5]
 array[2:2] = [item+5 for item in array]
 array
[1, 2, 6, 7, 8, 9, 10, 3, 4, 5]

Even more interesting

 array = [1, 2, 3, 4, 5]
 array[3:2] = ['new','members', 'in', 'the', 'list']
 array
[1, 2, 3, 'new', 'members', 'in', 'the', 'list', 4, 5]



Yours sincerely,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] iterate list items as lvalue

2007-08-20 Thread János Juhász
Dear Tutors!

I know a python list is a mutable object.
 array = [1,2,3,4,5]

So I can modify any item in it.
 for index in range(len(array)): array[index] *= 2
... 
 array
[2, 4, 6, 8, 10]

So I typed this:
 for item in array: item *= 2
... 
 array
[1, 2, 3, 4, 5]

It confused me a little, so made another test.
 item1 = array[0]
 item1
1
 item1 = 'changed'
 array
[2, 4, 6, 8, 10]
 item1
'changed'

So I feel that, the iteration goes over on inmutable objects.

But how can I iterate the iterate the items as mutable object, like the 
pointers in C ?
Is the only way to manage the iteration with indexes ?

Or is it any trick like
 for item in array[:]: item *= 2
... 

but isn't a trick :(
 array
[2, 4, 6, 8, 10]



Yours sincerely,
János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] from netcat to socket

2007-08-08 Thread János Juhász
Dear All,

I made a small script to emulate a jetdirect device and capture the data 
sent 
from SAP to three separate barcode printers. 
I need it to make backup for the SAP printing, as I can place the captured 

files onto a local server and place a small batch file beside them,
that can be used to print the files without SAP.
My first version worked with nc.exe (netcat) like so :

from threading import Thread 
import os
import time

printers = (('10.36.24.40', 'front'),
('10.36.24.41', 'gable'),
('10.36.24.42', 'top'))


class CaptureThread(Thread):
def __init__(self, address, type):
Thread.__init__(self)
self.setDaemon(True)
self.address = address
self.type = type
self.port = 9100

def run(self):
command = 'nc -l -s %s -p %d  %s.prn' %(self.address, self.port, 
self.type)
print command
os.system(command)
print '%s is printed' % self.type
time.sleep(2) #  wait for two seconds


def capture():
print_threads = []
for ip, name in printers:
print_thread = CaptureThread(ip, name)
print_thread.start()
print_threads.append(print_thread)
# now wait for them to finish
for print_thread in print_threads:
print_thread.join()

if __name__ == '__main__':
while 1:
print '-'*30
capture()
#do stuff with the saved files



I tried to change it to be socket based like so:

from threading import Thread 
import os
import time
import socket

## Settings
threads = {'front':{'capt':('127.0.0.1', 9100), 'dest':('127.0.0.1', 
9100), 'thread':None},
   'gable':{'capt':('127.0.0.1', 9101), 'dest':('127.0.0.1', 
9101), 'thread':None},
   'top':  {'capt':('127.0.0.1', 9102), 'dest':('127.0.0.1', 
9102), 'thread':None},
   }

class PrinterThread(Thread):
def __init__(self, address, port):
Thread.__init__(self)
self.setDaemon(True)
self.address = address
self.port = port
self.content = ''
self.soc = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.soc.bind((address, port))
self.soc.listen(1) 

def run(self):
try:
conn, addr = self.soc.accept()
while 1:
data = conn.recv(1024)
self.content += data
if not data:
conn.close()
break
except:
print 'exception (connection closed)'





So the question is, how translate 

command = 'nc -l -s %s -p %d  %s.prn' %(self.address, self.port, 
self.type)
os.system(command)

to be socket based.

I also would ask your opinions about the structure of 'threads'.


Regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ADO problem

2007-07-16 Thread János Juhász
Dear All,

I have a good sample about using ADO to reach windows active directory.

import win32com.client 
c = win32com.client.Dispatch(ADODB.Connection) 
c.Open(Provider=ADSDSOObject) 

rs,rc=c.Execute( 
SELECT name, description, department
From 'LDAP://DC=VELUX, DC=ORG' 
where objectClass='user' and name='*.ferbau' and department = 'IT'
order by name
) 

while not rs.EOF: 
print rs.Fields[0].Value, rs.Fields[1].Value
rs.MoveNext() 

It print the next result:
IT (u'\xc1kos Szab\xf3',)
IT (u'Szabolcs K\xe1m\xe1n',)
...

So rs.Fields[1] is a tuple.
I tried to turn it to get the first item from this tuple like this

while not rs.EOF: 
print rs.Fields[0].Value, rs.Fields[1][0].Value
rs.MoveNext() 

But it gives the next error 

Traceback (most recent call last):
  File D:\devel\python\admin\AD_ADO.py, line 13, in ?
print rs.Fields[0].Value, rs.Fields[1][0].Value
  File c:\Python24\Lib\site-packages\win32com\client\dynamic.py, line 
228, in
__getitem__
raise TypeError, This object does not support enumeration
TypeError: This object does not support enumeration


How can I print that unicode string?



János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ADO problem

2007-07-16 Thread János Juhász
Hi Tim,

thanks your help.
It is clear for me now.

 From: Tim Golden [EMAIL PROTECTED]
 Subject: Re: [Tutor] ADO problem

 J?nos Juh?sz wrote:
  while not rs.EOF:
  print rs.Fields[0].Value, rs.Fields[1].Value
  rs.MoveNext()
 
  It print the next result:
  IT (u'\xc1kos Szab\xf3',)
  IT (u'Szabolcs K\xe1m\xe1n',)
  ...
 
  So rs.Fields[1] is a tuple.

 Well, here's the most obvious thing:

 By the look of it: rs.Fields[1] is *not* a tuple.
 It's an instance of some sort. rs.Fields[1].Value
 *is* a tuple. So something like this:

 rs.Fields[1].Value[0]

 should work. I'm not quite clear why that second
 field returns a tuple while the first one doesn't.

Yes, It works.

So, I have to use
rs.Fields[1].Value[0] 
instead of
rs.Fields[1][0].Value


 To do this specific thing, you might find it easier
 to use a module wrapper:

 http://tgolden.sc.sabren.com/python/active_directory.html

 where your query would become something like (untested):

Your module works perfectly.
You should know something about the recordsets :)

 code
 import active_directory

 for user in active_directory.search (
 objectClass=User,
 name=*.ferbeau,
 department=IT
 ):
 print user.name, user.description, user.department
 
 /code

Regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 41, Issue 47

2007-07-13 Thread János Juhász
Hi Linden,



 Date: Fri, 13 Jul 2007 09:05:38 + (GMT)
 From: [EMAIL PROTECTED] [EMAIL PROTECTED]
 Subject: [Tutor] (no subject)
 To: tutor@python.org
 Message-ID:
 [EMAIL PROTECTED]
 Content-Type: text/plain; charset=utf-8

 The functionalities I am trying to implement for this purpose
 (aside from the more traditional ones of resetting, erasing text and
 quitting the program) are those that will enable the user to hear a
 sound (letter, word or whole sentence), write what he/she has heard
 in a text area, repeat it and wait for a corrected answer through a
 voice recognition and synthesis process. Can this be done in Python?

 Thank you in advance for any suggestion or answer, even
 partial, to my question.

About speech recognition in python take a look on this link:

http://win32com.goermezer.de/content/view/143/188/

And this is a working sample about the MS voice API

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] n.isalnum() is failing

2007-07-04 Thread János Juhász
Hi Terry

 According to the Gregorian calendar, which is the civil calendar in use
 today, years evenly divisible by 4 are leap years, with the exception of
 centurial years that are not evenly divisible by 400.

 def isLeapYear(y):
   if y % 4 == 0: return True
As it always return True, if y%4 == 0, there is problem with the 
exceptions
   if (y % 4 == 0) and not (y %100 == 0): return True
   else: return False


I feel that, the cleanest way to translate the definition into Boolean 
logic
is to do it backward instead of thinking on the exceptions. 

def leap_year(year):
if year%400 == 0: return True# We said these years are always leap 
year
if year%100 == 0: return False   # the exception handled already
if year%4   == 0: return True# no problem with the exceptions
return False # this it the default


ps
hungarians name format: family name, christian name
hungarian date format: year/month/day
Your logic is backward, and mine is the forward, isn't it?  ;)


Janos___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python port scanner

2007-06-25 Thread János Juhász
Dear dos,

hello i am looking into writing a simple python port scanner but i cant 
find
any good tutorials online if anyone can help or knows of any tutorials 
that
could help it would be great. this would be my first program like this 
so i
might need a little extra help

I just recommend to take a look on twisted 
http://www.oreilly.com/catalog/twistedadn/
It is a nice book.

There is an example on how to do it with twisted among the examples in 
chapter 2.


You can read it on safari.

Janos___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 40, Issue 38

2007-06-15 Thread János Juhász
Hi Andy,

 The code works great, Thanks for the speedy response. The only problem
 which I can see is that the code scales very bad with the size of n.

 So, as  I want a small subsection of the data (i.e lines where there are
 only 4 1s, number in the code below) for a system where n is large(20).
 The idea is that this  would reduce the number of iterations dramatic
 despite the individual loop taking longer to operate.(see example data).
 I've modified the bit_list_maker to allow for this but it has started to
 produce rows which are identical.
 Can anyone make any suggestion/improvements to the code

I feel that you would use this table for something else than simple print 
it.
It is probably a decision table.
As each cell of this table can be calculated anytime, I think to not store 
it in
any big table with a lot of integers in each cell, but simple calculate it 
at need.
You can save a lot of memory in that way.
If it is a decision table, I don't mind to starting the permutation on the 
first col
instead of the last. It doesn't change the permutation itself, just its 
order.

def Perm_matrix(row, col):
if (row  (2**col)): return 1
return 0

n = 4

for row in range(2**n):
for col in range(n):
print Perm_matrix(row, col),
print ';'


It is easy to turn it into a class.

class Perm:
def __init__(self, num):
self.rownum = 2**num
self.colnum = num

def Perm_matrix(self, row, col):
if (row  (2**col)): return 1
return 0

def __getitem__(self,(row,col)):
return self.Perm_matrix(row,col)

m = Perm(4)

for row in range(m.rownum):
for col in range(m.colnum):
print m[row, col],
print ''


Regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions of Maths

2007-04-18 Thread János Juhász
Hi Abu,

 Question: how to determine whether point C is to the left or to the
 right of the line AB?

When the line given by A(Xa,Ya) and B(Xb, Yb),
the area of the A-B-C triangle can be calculated with the value of next 
determinant / 2

| Xa, Ya, 1 |
| Xb, Yb, 1 |
| Xc, Yc, 1 | / 2

So:

Area = ( Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb) ) / 2

Area  0 | the points are clockwise (C is on the left)
Area  0 | the points are counterclockwise (C is on the right)
Area = 0 | the points are on the same line 


It can be written in a python function

###
def TriArea(a, b, c):
#Area = (Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb)) /2
return ( a[0] * (b[1]-c[1]) - b[0] * (a[1]-c[1]) + c[0] * (a[1]-b[1]) 
)/2

###
# to test it.
print TriArea((0,0), (10,0), (2,2))
print TriArea((0,0), (10,0), (2,-2))
print TriArea((0,0), (10,0), (2,0))
###


The biggest advantage of this calculation is that,
it never goes to zero division exception.



Best regards,
Janos
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Movies from jpg files

2007-04-08 Thread János Juhász
Dear Greg,

thanks the link to pymedia.

 Maybe PyMedia is what you are looking for:  http://www.pymedia.org

I looked for it for a while. It is very cool.
I made the next short script from one of the samples that make exactly 
what I wanted.

###

import sys, os, glob, Image, time
import pymedia.video.vcodec as vcodec

def files2Video(files, outFile='out.mpg', outCodec='mpeg1video'):
  s= Image.open(files[0])
  if outCodec== 'mpeg1video': bitrate= 270
  else:   bitrate= 980
  params= { 'type': 0, 'gop_size': 12, 'frame_rate_base': 125, 
'max_b_frames': 0,
'width': s.size[0], 'height': s.size[1], 'frame_rate': 2997,
'deinterlace': 0,'bitrate': bitrate, 'id': 
vcodec.getCodecID(outCodec)
  }
  e= vcodec.Encoder(params)

  fw= open(outFile, 'wb')
  for ActPic in files:
s= Image.open(ActPic)
ss= s.tostring()
bmpFrame= vcodec.VFrame(vcodec.formats.PIX_FMT_RGB24, s.size, 
(ss,None,None))
yuvFrame= bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P)
d= e.encode(yuvFrame)
fw.write(d.data)
  fw.close()

if __name__== '__main__':
files = glob.glob(r'.\test\*.jpg')
files.sort(key=lambda f:(os.stat(f).st_mtime, f))
files2Video(files, time.strftime('Cam1_%Y%m%d%H%M.mpg', 
time.localtime()))
[os.remove(f) for f in files]

###

Python is Cool :)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Movies from jpg files

2007-04-07 Thread János Juhász
Dear All,

I have found a fine Axis 2100 webcamera on my shelf, that was out of 
usage,
It uploads jpg images every minutes to an ftp server now.
I would like to build up a movie from the pictures for easier review.
I don't know which movie format can be built up easier,
.jpeg, quicktime .mov, .wmv, .avi or anything else.
It would be fine to use a format that has compression advantage compared 
the raw
volume of jpg files. It could be possible as the camera placed statically 
so the images
are very similar. 

May you recommend me which format could be used ?
May you recommend anything to build them easy ?


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Movies from jpg files

2007-04-07 Thread János Juhász
Dear Alan,


Alan Gauld wrote:
If you are usoing XP this is very easily done using MovieMaker.
Just drag n drop the jpg files into MM and adjust the durations.

Any of those programs will give you a choice of formats in
which to save the final movie.

Thanks your response.
It should works well with some images, but I would do it with a scheduled 
way
with some 1000 files.

So, I have to extend my prev. post.

---
I have found a fine Axis 2100 webcamera on my shelf, that was out of 
usage,
It uploads jpg images every minutes to an ftp server now.
I would like to build up a movie from the pictures for easier review.
I don't know which movie format can be built up easier,
.jpeg, quicktime .mov, .wmv, .avi or anything else.
It would be fine to use a format that has compression advantage compared 
the raw volume of jpg files. It could be possible as the camera placed 
statically
so the images are very similar.

May you recommend me which format could be used ?
May you recommend anything to build them easy ?
---

I have some thousand images, so I would use some kind of script to do it.
May you recommend any python library to build any kind of movies from a 
folder of
jpg files?
It could be any commandline tool anyway, that I can call with os.system(),
but I wouldn't use GUI for it.


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making table

2007-03-20 Thread János Juhász
Dear Barry,

Using a formatting string of %10.4f, these would be rendered as:

   '  253.'
   '   77.6000
   '9.0300'
   '0.0210'

This formatting gives the impression that all values but the last are
more precise than they truly are.  A scientist or statistician would
prefer to see something like this:

   '254.'
   ' 77.6   '
   '  9.03  '
   '  0.0210'

Does numpy or some other math package have that capability?

You can use advanced regexp, called lookaround, lookbehind for this 
purpose.

###

import re

l = (253., 77.6, 9.03, .0210, 1000, 100.1230)
ending_zero = re.compile('0(?=0*$)') # zero followed with only zeros

for f in l:
print re.sub(ending_zero, ' ', ('%10.4f' % f))

###




Yours sincerely,
__
János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should I use python for parsing text

2007-03-20 Thread János Juhász
Hy Jay,

I just allways wonder how fine this book about text processing with 
python.

Text Processing in Python at http://gnosis.cx/TPiP/

It shows that Python can be as effective as Perl. The question is the how.
Take a look on it.


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Roman to digital (pseudocode)

2007-03-14 Thread János Juhász
Hi All,


 - A dictionary will help you look up values, but not rules. It does
 not retain its order and order is essential. Instead, create a tuple
 of the roman numerals in ascending order (roman). Create a paired
 tuple with the base 10 value (baseten).

 Now get an element from the string you want to test -- use the index
 value in roman to test the rules -- you will know what is higher,
 lower, and the same

 Then look for things like the following:

 - does the following element have a lower index in roman? if yes, you
 know the value (match indexes from the tuples) -- step forward
 - what if the follower is the same? then check the one after, if it is
 the same (and the following digit is lower) then you have a value. --
 step over the last matching digit
 - if the following value is higher, it must be by only one unit, if so
 you have a value, but also a new rule: the following digit must be
 lower than the last digit of the pair.

 and so on.
 not pseudocode I know, and I am certain there are better ways to do
 this, but maybe something here helps.


#
roman_codec = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}

original = raw_input('Enter a roman number:')
roman = original.upper()
roman = list(roman) # I would like to use pop instead roman = roman[1:]
roman.reverse() # pop picks from the end, so prepare for it
decimal = [roman_codec[ch] for ch in roman] # turn the chars into decimal

result = 0

while len(decimal):
act = decimal.pop()
if len(decimal) and act  max(decimal): act = -act # if there is a 
char with higher score it is minus :)
result += act

print original, '=', result


Python is nearly pseudocode.
This is the reason we like it so much.


Best regards,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] howto call DOM with python

2007-02-28 Thread János Juhász
hi

there are same samples about it in the activepython 2.4 installation 
folder
c:\Python24\Lib\site-packages\win32comext\axscript\Demos\client\ie\
on my xp, but it isn't working. I have just repaired my activepython and 
reinstalled it but no success.

As I remenber, it was working under activepython 2.3 anyway.


Yours sincerely,
__
János Juhász


 Date: Wed, 28 Feb 2007 15:40:59 -0600
 From: Hugo Gonz?lez Monteverde [EMAIL PROTECTED]
 Subject: Re: [Tutor] howto call DOM with python
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 I too wish it worked. In javascript, it works because the browser has a
 Javascript implementation. There's no stock browser with a Python
 implementation, and I've looked for any client side implementation with
 no success.

 Hugo

 Ismael Farf?n Estrada wrote:
  hi there
 
  I was wondering wheter someone knows how to use python to write
  a client-side scripts like if it were java, I want to get someting 
like
  this working
  html
  script type=text/python
  window.alert(python)
  /script
  /html
 
  but nothing happens. I don't know javascript but this code works
  if I put javascript instead of python, I've also tried with 
pythonscript
  python-source, etc
 
  hope you can help me, I'm using GNU/Suse, Opera, and Firefox for test
 
  _
  El mejor destino, con los mejores contenidos 
http://www.prodigy.msn.com
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] report service

2007-02-19 Thread János Juhász
Dear Kent,


  May someone recommend any simple solution to distribute some dozen
  parametrizable sql reports
  for some dozen users with a minimal access controll.
  Some kind of charting possibilty needed, but I needn't web-based front 
end.

 I'm not sure I understand your requirements. Do you want a way for a
 dozen users to be able to create reports from a database, where they
 select some parameters and create the report on demand?

Currently I have some crystal reports, some dozen excel tables with simple 
or complicated 
database queries and some delphi programs with some grids and sometimes 
with charts. 
All of these 'reports' and it's contents are managed by the IT department.
My dream to have a central repository of database reports, 
organized based on the workflow and controlled by the controlling 
department.
The distribution can be made by filesystem level (each report a separate 
file),
or by application level (the report manager shows a tree with the 
accessible reports).

The candidates are till now:
 crystal report server
 ms reporting services
 commercial reportlab



Yours sincerely,
__
János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] report service

2007-02-18 Thread János Juhász
Dear All!

May someone recommend any simple solution to distribute some dozen 
parametrizable sql reports 
for some dozen users with a minimal access controll.
Some kind of charting possibilty needed, but I needn't web-based front 
end.


Yours sincerely,
__
János Juhász
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] min max confusion

2007-02-07 Thread János Juhász
Hi Frank,


 From: frank h. [EMAIL PROTECTED]
 Subject: [Tutor] min max confusion

  t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
  min(t)
 939L
  max(t)
 exceptions.TypeError Traceback (most 
recent
 call last)
 TypeError: 'int' object is not callable

 
 why doesn't max(t) work?! I am using python 2.4.4
 thanks for any insight you might have
 -frank


 t = (952L, 945L, 941L, 939L, 949L, 972L, 956L, 965L, 973L, 965L)
 min(t)
939L
 max(t)
973L

So it should works fine.

 help(max)
Help on built-in function max in module __builtin__:

max(...)
max(sequence) - value
max(a, b, c, ...) - value
 
With a single sequence argument, return its largest item.
With two or more arguments, return the largest argument.

The max() function should be overwritten like this:

 def max(a, b):
... print b
... 

And it can be checked easy.

 help(max)
Help on function max in module __main__:

max(a, b)

 

In this case, you can use the original builtin max() so:

 __builtin__.max()


Best regards,
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Printing txt files in landscape from python

2007-02-01 Thread János Juhász
Hi All,

do you have any idea, how I can send a txt file to the default printer in 
landscape view with python on windows.
I wanted to set up just the char size and the orientation of the printout.

thinking about
os.system('notepad.exe /pt %%%s' % filename)


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Cause-Effect, Isikawa, fishbone diagram

2007-01-24 Thread János Juhász
Dear All,

does someone know any python based solution to draw a 
cause-effect diagram into PDF from a simple textfile ?

It is also called a Fishbone Diagram, because of its shape, 
or an Ishikawa Chart, after its originator, Kaoru Ishikawa
I feel, it can be converted from a structure like this.

Title
Effect
  Cause1
Secundary
  Tertiary
  Tertiary
  Cause2
Secundary
  Tertiary
  Cause3
Secundary
  Tertiary

It is probably a simple function.



Yours sincerely,
__
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] direction and draw

2007-01-22 Thread János Juhász
Dear Linda,

 I have a segment (two ending points are A and B) which is 0 degree.
 How to draw a segment with 10 degrees and 15 in length?
It is very simple with complex numbers:

import math

class vect:
## begin and end are tuples (x, y)
## and represented as complex numbers
def __init__(self, begin, end):
self.begin = complex(begin[0], begin[1])
self.end = complex(end[0], end[1])

def Rotate(self, deg=0):
rad = math.radians(deg)
rot = complex(math.cos(rad), math.sin(rad))
self.end = self.begin + (self.end-self.begin)*rot

def SetLength(self, length):
dist = self.end - self.begin
actlength = math.sqrt(dist.real**2 + dist.imag**2)
dist = dist * length / actlength
self.end = self.begin + dist

def __str__(self):
return '(%.2f, %.2f)-(%.2f, %.2f)' % \
   (self.begin.real, self.begin.imag, self.end.real, 
self.end.imag)


v = vect((10,0),(20,0))
print 'orig:', v
v.Rotate(10)
print 'rotated:', v
v.SetLength(15)
print 'sretched:', v



It seems to be a kind of homework, 
but I wanted to test how can I response in a thread.

All of my earlier responses started new threads in this list like this 
http://mail.python.org/pipermail/tutor/2007-January/052169.html.

Have I remove the '[Tutor]' or '[Tutor] ' from the subject of the response 
? 
Do I need any special about the mail in notes ?


[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Geoframer 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Danny Yoo 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Kent Johnson 
[Tutor] 'elp!!!1Totally Clueless Newbie In Distress   Karl 
Wittgenstein 


I don't understand how these threads are built up. The subject fields 
seems to be identicals.
Is there used anything else than the subject field for recognize the base 
of the response ?

RTFM about how to respond to this list is welcomed with valuable links.


Regards:
___
Janos Juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress

2007-01-21 Thread János Juhász
Dear Karl,


I use getch() when I start my script from the windows desktop and 
I am interested about its output.

import msvcrt
raw_input('Are you distressed ?\n')
print ('It will be better, I am sure :)')
msvcrt.getch() # append as last line

 Subject: Re: [Tutor] 'elp!!!1Totally Clueless Newbie In Distress
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii

 * Karl Wittgenstein [EMAIL PROTECTED] [2007-01-20 13:10]:
  Ok,got the script working almost fine now...The only problem is that 
the
  program window closes before we can get a glimpse of the answer...I 
use SPE
  under WinXP, and have seen this problem in every script i try...This 
is the
  script,as redone by a Smart Caring Dude on this list:


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] import glob.glob('*.py')

2007-01-08 Thread János Juhász
Hi All,

I am playing with reportlab and I would like to make a directory where I 
can place all of my projects as ___.py files.
A project file should be like this:
test.py
title=Test project
duedate = '2007-02-28'
description = description _
detailed=
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed
detaileddetaileddetaileddetaileddetaileddetaileddetailed

test.py

I plan to make a python script, that collect all the projectfiles from 
that folder and render them as a report summary.
I planned to import these files as modules like 

for filename in glob.glob('*.py'):
if '_' in filename: continue
import filename
render(filename)

Probably you have better ideas to do that.


Yours sincerely, 
__
Janos Juhasz 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Find and test a device by MAC address

2007-01-05 Thread János Juhász
Dear Lumbricus,

 From: [EMAIL PROTECTED]
 Subject: Re: [Tutor] Find and test a device by  MAC address
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1

 Quick and dirty:
 As root:
  from scapy import *
  arping(192.168.0.1/24) # or whatever fits to your network
 and then filter the answers; or build your own arp packets with ARP().

I have an XP, so I made a simple ping for the topmost IP address, 
that is the broadcast address in my subnet and I run an arp -a.

Thanks for the hint for scapy.

http://www.secdev.org/projects/scapy/ seems to be very very cool.

Some months earlier someone tried to collect how many application made in 
pure python.
The list should be extended with scapy as a pure python application.

Thanks Lumbricus.

Yours sincerely, 
__
Janos Juhasz 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 3D rendered bar chart (made of glass)

2006-11-06 Thread János Juhász
Dear Guys,

I have downloaded CGkit and Aqsis and tried the examples from it.
I run the samples, like the torus with grass. It is simple fantastic.
I would like to make some artistic visualization with the power of python 
and the beauty of a professional renderer. 
I think about colored semitranslucent glass cubes.
Like a simple bar graph, but the cube's 3D position, extension, color and 
text would be defined by database content and some calculus.
It would be fine to make some axes and making the 3D view settings in an 
interactive 3D program.

May you recommend any simple solution about it ?


Yours sincerely, 
__
Janos Juhasz 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to extract the last line of a text file

2006-10-20 Thread János Juhász
 Danny Yoo wrote:
 
  file('filename.txt').readlines()[-1]
  Not to hijack the thread, but what stops you from just putting a
  file.close() after your example line?
  Which file should file.close() close?  The problem is that we don't
  have a handle on the particular file we want to close off.
 
  Oh wow.. I totally missed that... nevermind.. ignore that question =D
 
 
  Hi Chris,
 

 Wow, that seems like overkill when you can just write
 f = open('filename.txt')
 f.readlines()
 f.close()

 In CPython (the regular Python that we usually talk about here,
 implemented in C) a file will be closed automatically as soon as there
 are no references to the file because CPython garbage collects objects
 immediately. This behaviour is not guaranteed by the language though and
 it is different in Jython.
 
 
  This is similar in spirit to the idea of autorelease memory pools 
used
  by the Objective C language.  We use some resource manager that does
  keep a handle on resources.  That manager then has the power and
  responsiblity to call close() at some point.  So one might imagine 
doing
  something like:
 

 In Python 2.5 you can use with: to do this:
 with open('filename.txt') as f:
 f.readlines()
 
 f is guaranteed to be closed when the block exits.
 Kent

I made a small test about, what could happen with a file object,
that was opened for read, but left without closing.

# we need to put something into the test file
 fw1 = open(r'test.txt', 'w')
 fw1.write('written by fw1')
 fw1.close()
# so we have the test file

# we can open and read from it
 fr1 = open(r'test.txt', 'r')
 fr1.readlines()
['written by fw1']
# I left it opened.

# Another instance could be opened for read again
 fr2 = open(r'test.txt', 'r')
 fr2.readlines()
['written by fw1']
# I left the second instance opened eighter

# Someone rewrite the content of the file
 fw2 = open(r'test.txt', 'w')
 fw2.write('written by fw2')
 fw2.close()
# I closed it correctly after writing

# The instance opened for reading could be reread
 fr1.seek(0)
 fr1.readlines()
['written by fw2']


 fr2.readlines()
[]

# I have extended it a little
 fw2 = open(r'test.txt', 'w')
 fw2.write('written by fw2 but it is extended later')
 fw2.close()


 fr2.read()
' but it is extended later'
 

I feel that, we can left opened files with open(filename).readlines() in a 
number of times,
but would be problematic to do it 100 000 times in the same script.


Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] regexp help needed

2006-10-18 Thread János Juhász
Dear All,

I have a problem about the EDI invoices created by our erp system.
I have to make a small correction on them, just before sending them by 
ftp.

The problem is that, the big numbers are printed with thousand separator.

U:\ediout\INVOIC\Backupgrep \, *.doc
File 063091.doc:
 MOALIN203   79.524,480 DKK4
 PRI   YYY   1.095,130   1PC
 MOATOT79  594.629,400  DKK4
File 063092.doc:
 MOALIN203   47.281,680 DKK4
 MOATOT86   56.738,016  DKK4
 MOATOT79   47.281,680  DKK4

I have to remove the thousand separator by moving the numbers before it to 
right.
So the number and char groups has to be left in their original position.

I have to make this kind of changes on the problematic lines:
 MOATOT79   47.281,680  DKK4
 MOATOT7947281,680  DKK4

I have no idea how to make it :(

__
János Juhász 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp help needed

2006-10-18 Thread János Juhász
Hi Kent,

thanks your respond.

  I have to remove the thousand separator by moving the numbers before 
it to
  right.
  So the number and char groups has to be left in their original 
position.
 
  I have to make this kind of changes on the problematic lines:
   MOATOT79   47.281,680  DKK4
   MOATOT7947281,680  DKK4
 
  I have no idea how to make it :(

 Break it up into smaller problems:
 for each line in the data:
 break the line up into fields
 fix the field containing the amount
 rebuild the line
 
 You don't really have to make a regex for the whole line. re.split() is
 useful for splitting the line and preserving the whitespace so you can
 rebuild the line with the same format.

 Kent

I can't find the way to preserve the whitespace at split.

But I found a way to use regexp.

import re
# this is a group of numbers, followed by a dot, followed by 3 numerics 
and a comma
pat = re.compile(r'(\d+)\.(\d{3},)')

def replace_thousand_separator(line):
# when the '.' removed a space has to be prepended
return re.sub(pat, r' \1\2', line)

for file in glob.glob('*.doc'):
lines = open(file, 'r').readlines()
lines = [replace_thousand_separator(line) for line in lines]
open(file, 'wt').writelines(lines)



Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me with two dimensional arrays in Python

2006-10-09 Thread János Juhász
Dear Asrarahmed,

I have found the next recipe in the cookbook.
It should be interesting for you :)

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/392153

 Message: 1
 Date: Thu, 05 Oct 2006 10:26:19 -0400
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] Help me with two dimensional arrays in Python
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 Asrarahmed Kadri wrote:
  Its something very close.
  What I want is:
 
  1
  1 1
  1 2 1
  1 3 3 1
  1 4 6 4 1



Yours sincerely, 
__
János Juhász 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Point in polygon intro please~!

2006-10-09 Thread János Juhász
Hi Michael,


 Subject: Re: [Tutor] Point in polygon intro please~!
 To: Michael Shulman [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed

 Michael Shulman wrote:
  Hello, I'm very new to both python and OpenGL, but I'm catching on
  pretty quick,
  and trying to make a little game.  I'm stuck on being able to do this
  point-in-polygon test though.
  Everyone seems to say that I should create a ray and see how many 
sides
  of a polygon it intersects, (even vs odd)
  but I have no idea how to go about setting this up.


If you would like to get the 3D object, that belongs to the given pixel, 
OpenGL gives a simpler way for it with glRenderMode(GL_SELECT);

Converting the 3D objects to poligons, seems to be too difficult,
and not needed.


Take a look after the GL_SELECT mode

http://www.google.hu/search?hl=huq=glRenderMode%28GL_SELECT%29meta=



Yours sincerely, 
__
János Juhász 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pymssql or ODBC

2006-09-15 Thread János Juhász
I am using the next two solution for connecting to our mssql server

when the odbc connection is set for all the PCs, I use this:

import dbi, odbc
cn = odbc.odbc('DSN=scalaDB;UID=query;PWD=query;DATABASE=DB') 

When there is no connection set and distributed, I usually choose this 

import win32com.client 
cn =win32com.client.Dispatch('ADODB.connection')
cn.Provider='sqloledb'
cn.Open('Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security 
Info=False;Initial Catalog=production;Data Source=MyServername')

To create the correct connection string I follow this simple method:
-right click on the desktop and create a new text document
-save it as connection.udl
-double click on it, and it will be opened by windows to set up all the 
possible parameters
-test the connection
-open it with notepad and copy the string from it



Yours sincerely, 
__
János Juhász 


 [Chris Hengge]
 | Does anyone know how to make pymssql use windows authentication?

 I'm fairly sure, from previous experience and a brief
 perusal of the source, that pymssql doesn't offer the
 possibility of pass-through authentication. When I use
 it, I have to ask my DBA to set up a specific user.

 The usual place to look for connection strings for
 ODBC, ADO etc. is http://connectionstrings.com. I just
 tried downloading the latest mxODBC and using the connection
 string from there, only to get an internal error... I'll try
 a new download just in case.

 But you've also got ADO: the adodbapi module, while unmaintained,
 does in fact work. It's a mite quirky, due partly from having to
 work round variations in ADO versions. But we do use it for
 pass-through authentication. (connectionstrings.com again for DSN).

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Clipboard manager for windows

2006-09-14 Thread János Juhász

Hi Derick,

So I need a way to hijaak the Ctrl-C and Ctrl-V
shortcuts and have my
application run in the system tray. I don't need
a gui other than changing
the context menu (which I believe is done in the
registry) - although, I'd
probably need to use wxPython for using the system
tray - unless by catching
the shortcut keys, I can call the program...

I have tested it without hijaak the Ctrl-C and Ctrl-V
It is seem to be easier to set up a shortcut to in-place
filtering
on the current content of the clipboard.

I just have played with the sample you showed:


### text.py My small clipboard coverter ###
import win32clipboard as w 
import win32con
import re

def getText(): 
  w.OpenClipboard() 
  d=w.GetClipboardData(win32con.CF_TEXT)

  w.CloseClipboard() 
  return d 

def setText(aType,aString): 
  w.OpenClipboard()
  w.EmptyClipboard()
  w.SetClipboardData(aType,aString) 
  w.CloseClipboard()

def myFilter(text):
  comma = re.compile(',')
  return comma.sub('\t', text)

def myTester(text):
  ### context sensitivity
  return ',' in text
  
text = getText()
if myTester(text):
  setText(win32con.CF_TEXT, myFilter(text))
### My small clipboard coverter ###

I have saved this python script into my devel folder,
created a shortcut on the windows desktop,
set up a shortcut key for it with Ctrl-Alt-T.
When I start this program with the shortcut key, it
simple makes 
the replace in-place on the current content of the
clipboard, 
that can be put into excel after it.

Copy this to the clipboard:
a,b,c,d,e
1,2,3,4,5
run the script
Paste the clipboard to excel
Viola :)

You can make it with wxPython and give the choice
for the
user on the visual surface to choose from more filters.

It also could be interesting, to
make the tab delimited clipboard content from the filenames.
 w.OpenClipboard()
 w.GetClipboardData(win32con.CF_HDROP)
(u'D:\\devel\\tutor\\data.txt',)
 w.CloseClipboard()




Yours sincerely, 
__
János Juhász 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Thread forever ?

2006-09-07 Thread János Juhász

Dear Tutors,

###
from threading import Thread
import sys
import time

# This thread would read lines from a
# barcode scanner
class ComThread(Thread): 
  def __init__(self):
Thread.__init__(self)

  def run(self):
while 1:
  time.sleep(2)
  print time.ctime()

com = ComThread()
com.start()

# Main loop for handling the keyboard
while 1:
  s = raw_input()
  if s == '': continue
  elif s in 'qQ':
# may I com.Terminate()
here
sys.exit()
# when I goes out here
# the comthread is just
running.
  else:
try:
  num = int(s)
  print 'mod
qty=%d' % num
except:
  pass
#

When this program leaves from the
while loop, it doesn't terminate the comreader thread.
It can be terminated with the 'X'
at the topright corner, but it seems to be not the best way.


Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Thread forever

2006-09-07 Thread János Juhász

Dear Kent,

thanks your comment.

  When this program leaves from the
while loop, it doesn't terminate the 
  comreader thread.

If you call self.setDaemon() here you will
mark the thread as a daemon 
thread and it will not block the exit of the program.

It works well.

Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python decorator

2006-08-31 Thread János Juhász

Hi,

I have just started to play with
TurboGears - it is really nice - and I couldn't understand the decorators
used by it.
I have tried to interpret the http://wiki.python.org/moin/PythonDecorators
about decorators, but it is too difficult for me.

May someone explain decorators
in very sortly, what is it for and why ?
Do I need it anyway ?

Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Banner

2006-08-27 Thread János Juhász

Hi all,

I just profiled a little my banner.py.

# PIL_Banner

import Image, ImageFont, ImageDraw

ShowText = 'Python :)'

font = ImageFont.load(r'courier-bold-12.pil')
size = font.getsize(ShowText)
image = Image.new('1', size, 1)
draw = ImageDraw.Draw(image)
draw.text((0, 0), ShowText, font=font)
for rownum in range(size[1]):
  line = []
  for colnum in range(size[0]):
if image.getpixel((colnum,
rownum)): line.append(' '),
else: line.append('#'),
  print ''.join(line)

#image.show()

I have just recognized that, the
pil font files are missing from the PIL distribution, so I have atteched
a pil font, that has to be placed beside the script.



So, it will create the next response:

 
### 
  
#
## ##
 ##
 ##
## ##   
 ##  ##   
  ##
## ## # ## ##
  ## ###  ##  
##
## ## ## ## ##
 ### ## ## ## ### ## ##
  ##
# ## # 
##  ## ## ## ## ## ##   
 ##
##    
##  ## ## ## ## ## ##   
 ##
##   ### 
## # ## ## ## ## ## ##   
 ##   ##
#   ##  
### ### ###   ## ## 
 ##
##
  
  
 ##
##
  
  
 #



Yours sincerely, 
Janos Juhasz 

courier-bold-12.png 
Description: Binary data


courier-bold-12.pil 
Description: Binary data
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A list in list problem

2006-08-21 Thread János Juhász

Hi Dave,

 From: dave s [EMAIL PROTECTED]
 Subject: [Tutor] A list in list problem
 To: python tutor tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii

 def CSV_Lines(self, csv, from_, to):
 Returns a list of cleaned up lines from csv 'from_'
line
 number 'to' line number

 clean_line
= clean_csv = []
 for string in range(from_, to):
  
  split_string = csv[string].split(',')
 split_string
= split_string[1:-1] # Strip the LHS column + the /n'
  
  if split_string[0] == '' : continue # Skip
empty lines
 print
'##'
 print
'split_string ', split_string
 for
string in split_string:
  
  if len(string)
 0: clean_line.append(string[1:-1])
 print
'clean_line ',clean_line
 clean_csv.append(clean_line)
 print
'clean_csv ',clean_csv
 clean_line
= []
 
 But I get clean_csv trouble ...

 [EMAIL PROTECTED]:~/python_develop/unison/PxQxAudit/main$
./crosscheck.py
 ##
 split_string ['temp1', 'wow a variable',
'', '', '']
 clean_line ['temp1', 'wow a variable']
 clean_csv ['temp1', 'wow a variable', [...]]
 ##
 split_string ['temp2', '', '', '', '']
 clean_line ['temp2']
 clean_csv ['temp1', 'wow a variable', [...], ['temp2']]
 [EMAIL PROTECTED]:~/python_develop/unison/PxQxAudit/main$

 ie clean_csv ends up as ['temp1', 'wow a variable',
[...], ['temp2']] instead
 of [[temp1, wow a variable], [temp2]]


You have used string as variable name two times, once
as an integer and once as a field in the line.
It should be avoided.

I like list comprehension in this case.

def CSV_Lines2(csv, from_, to):
  csv = csv[from_ : to]  
   
   
  # We are interested just here
  csv = [line.split(',') for line in csv]
# Make a 2D array from the list
  return [LineItems[1:-1] for LineItems
in csv if len(LineItems)  2] 
 
# filter out first and last columns,
and lines with too less items



csv = Header1
Header2
temp1,12,20,1
temp2,22,22,2
temp3,33,44,3
temp4,34,64,4
Footer1
Footer2

csv = csv.split('\n')
print CSV_Lines2(csv, 2, 6)
[['12', '20'], ['22', '22'], ['33', '44'],
['34', '64']]


Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Build a simple ftp server in python

2006-08-16 Thread János Juhász

Hi All,

I am just plannig to make a small
ftp server that would serv not a filesystem, but some kind of objects,
like stocks or assets.
In that case I can use my favorite
commander to delete, copy, move objects from one place to another.

Have you got any idea which module
to use ?

Yours sincerely, 
__
János Juhász ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system() with NO_WAIT

2006-08-08 Thread János Juhász

Thanks Wesley,

I lokked for
subprocess.Popen.

os.spawnlp(os.P_NOWAIT, /bin/mycmd, mycmd,
myarg) was to complicated for me based on the manual.


Yours sincerely, 
__
János Juhász 
VELUX Magyarország Fertődi Építőkomponens Kft. 
IT Department
Malom Köz 1, H-9431 Fertőd 
Telephone direct:  
+36 99 537 939
Telephone office:   +36 99 537 920
Office fax:+36
99 537 921
Telephone mobile:  +36 30 682 6331
@  
[EMAIL PROTECTED]
www  
 www.VELUX.com






wesley chun [EMAIL PROTECTED]


2006.08.07 22:28



To
János Juhász
[EMAIL PROTECTED]

cc
tutor@python.org

Subject
Re: [Tutor] os.system()
with NO_WAIT



 os.system('vedicom.exe')

 Have you got any idea how I can strart this windows GUI program with
not
 waiting its return.

instead of os.system(), you want to use the subprocess
module if you
are using Python 2.4+:
http://docs.python.org/lib/module-subprocess.html

calling subprocess.Popen([/bin/mycmd,
myarg]) is no wait.

to save the PID:

pid = subprocess.Popen([/bin/mycmd, myarg]).pid

if you are using Python 2.3.x and older, you have
to use spawn*():

pid = os.spawnlp(os.P_NOWAIT, /bin/mycmd,
mycmd, myarg)

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.system() with NO_WAIT

2006-08-07 Thread János Juhász

Dear Guys,

I have a small script that is running on a terminal
server's client session.

###
import os
import time
import glob

def send():
  print 'I am checking %s' % time.ctime()
  if len(glob.glob(r'U:\ediout\DESADV\*.doc'))
 0:
os.system('vedicom.exe')

if __name__ == '__main__':
  os.chdir(r'U:\vedicom\DESADV\\')
  while 1:
send()
time.sleep(30)
###

As you can see, it is just start
a windows program from a folder, when there are files in that folder.
My problem comes when the network
connection is broken. In that case, this program wait a user interaction
to push a button.
When the connection come back,
it is just waiting to push the button and we are missing to send the EDI
documents.

Have you got any idea how I can
strart this windows GUI program with not waiting its return.




Yours sincerely, 
__
János Juhász 
VELUX Magyarország Fertődi Építőkomponens Kft. 
IT Department
Malom Köz 1, H-9431 Fertőd 
Telephone direct:  
+36 99 537 939
Telephone office:   +36 99 537 920
Office fax:+36
99 537 921
Telephone mobile:  +36 30 682 6331
@  
[EMAIL PROTECTED]
www  
 www.VELUX.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 29, Issue 68

2006-07-27 Thread János Juhász

Dear Alan,

  It works now from Python prompt. I just
wanted to put this
  functionality
  into a small wxpython application and building up the menus like
  pythoncard.

 And Ok with this I think, but
 Are you actually using PythonCard or are you using wxPython directly?

wxPython directly.

  So, when there was a functionname like OnMenuShowAssetNumber,
  I would append a new menuitem with ShowAssetNumber.

 OK, But I still don't see why you need getattr.
 Its your code, you know what the functions are, you can build
 the menu directly. Why use getattr?

 Alan G.

It just tried to do it another way.
There is a file for wx, and another for visio, they
aren't joined together.
wx is filled up based on the functionnames of the
other.


class ShellFrame(wx.Frame): 
  def __init__(self, parent=None, id=-1,
title='PyCrustVisio'):
...
self.FillUpMenu()

  def FillUpMenu(self):
MenuItems = [item for
item in dir(visio) if item.startswith('OnMenu')]
for FunctionName in MenuItems:
  menuID =
wx.NewId()
  menuText
= FunctionName[6:]
  self.menu.Append(menuID,
menuText, menuText)
  self.Bind(wx.EVT_MENU,
getattr(visio, FunctionName), id=menuID)



So I can write it with this way:
self.Bind(wx.EVT_MENU, getattr(visio, FunctionName),
id=menuID)

Every function in the visio module
starting with 'OnMenu' will be appeared in the application menu.

Probably its a bad habit, but it
is just for trial.



Yours sincerely, 
__
János Juhász 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getattr()

2006-07-26 Thread János Juhász

Dear All,

I want to use getattr() to collect
a list with all the functions on my simple script those has got some functionname
like 'On'.

#This should be the complete file
def OnMenuFindMe():
  print 'You found me'

f = getattr(What_Should_It_Be???, 'OnMenuFindMe')

f()
#Till here

It can use getattr() to get an
object of a class or module, but not in this much simpler situation.



Yours sincerely, 
__
János Juhász 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getattr()

2006-07-26 Thread János Juhász

Dear Kent,

You can look up the function in the globals()
dict, or you can import 
__main__, which is the top-level module, and use getattr() on it.
Or you 
could wrap your functions in a class...

def OnMenuFindMe():
  print 'You found me'

f = globals()['OnMenuFindMe']

f()

import __main__

g = getattr(__main__, 'OnMenuFindMe')
g()

Kent

Many thanks.


Yours sincerely, 
__
János Juhász 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with strings and lists.

2006-07-14 Thread János Juhász

Dear Alan,

Probably you will be interested
about list comprehension and zip(), as it can simplify all the similar
tasks.

 s = ('Monday 7373 3663657 2272 547757699
reached 100%','Tuesday 7726347 552 766463 2253 under-achieved 0%','Wednesday
9899898 8488947 6472 77449 reached 100%','Thursday 636648 553 22344 5699
under-achieved 0%','Friday 997 3647757 78736632 357599 over-achieved 200%')
 # I made a table from your list
 table = [line.split() for line in s]
 # it is possible to transpose the table
 transposed = zip(*(table))
 transposed
[('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'),
('7373', '7726347', '9899898', '636648', '997'), ('3663657', '552', '8488947',
'553', '3647757'), ('2272', '766463', '6472', '22344', '78736632'), ('547757699',
'2253', '77449', '5699', '357599'), ('reached', 'under-achieved', 'reached',
'under-achieved', 'over-achieved'), ('100%', '0%', '100%', '0%', '200%')]
 # calc the max(len(str(cell))) for each
row,
 # that means columns in the original
table
 maxWidths = [max([len(str(cell)) for
cell in column]) for column in transposed]
 maxWidths
[9, 7, 7, 8, 9, 14, 4]
 # format it
 [ str.ljust(str(field),w) for (field,
w) in zip(table[0], maxWidths)]
['Monday  ', '7373  ', '3663657', '2272
 ', '547757699', 'reached', '100%']
 # join it to give a line
 '|'.join([ str.ljust(str(field),w) for
(field, w) in zip(table[0], maxWidths)])
'Monday  |7373  |3663657|2272  |547757699|reached
   |100%'
 # it can be made for all of the lines
 '\n'.join(['|'.join([ str.ljust(str(field),w)
for (field, w) in zip(line, maxWidths)]) for line in table])
'Monday  |7373  |3663657|2272  |547757699|reached
   |100%\nTuesday |7726347|552  |766463
|2253   |under-achieved|0% \nWednesday|9899898|8488947|6472
 |77449  |reached|100%\nThursday
|636648 |553  |22344  |5699   |under-achieved|0%
\nFriday  |997  |3647757|78736632|357599 
|over-achieved |200%'
 # and can be printed in this form
 print '\n'.join(['|'.join([ str.ljust(str(field),w)
for (field, w) in zip(line, maxWidths)]) for line in table])
Monday  |7373  |3663657|2272  |547757699|reached
   |100%
Tuesday |7726347|552  |766463 |2253
  |under-achieved|0% 
Wednesday|9899898|8488947|6472  |77449
 |reached|100%
Thursday |636648 |553  |22344  |5699
  |under-achieved|0% 
Friday  |997  |3647757|78736632|357599
 |over-achieved |200%
 

I know it is a different way of
thinking, but it works well with python.
It is the functional way instead
of your procedural one.

 Hi,

 I do a far bit of data manipulation and decided
to try one of my
 favourite utilities in Python. I'd really appreciate some optimization
 of the script. I'm sure that I've missed many tricks in even this
short
 script.

 Let's say you have a file with this data:

 Monday 7373 3663657 2272 547757699 reached 100%
 Tuesday 7726347 552 766463 2253 under-achieved 0%
 Wednesday 9899898 8488947 6472 77449 reached 100%
 Thursday 636648 553 22344 5699 under-achieved 0%
 Friday 997 3647757 78736632 357599 over-achieved 200%

 You now want columns 1, 5, and 7 printed and
aligned (much like a
 spreadsheet). For example:

 Monday  547757699 100%
 Wednesday   77449 100%
 ...

 This script does the job, but I reckon there
are better ways. In the
 interests of brevity, I have dropped the command-line argument handling
 and hard-coded the columns for the test and I hard-coded the input
file
 name.


 Any help greatly appreciated.
 Regards,
 Alan.

Best Regards,
János Juhász___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] I Give Up. - Follow up post

2006-07-05 Thread János Juhász
Dear Brian,

The best parser is python itself :)

let's make ports.py with your original content:
http = 80
https = 443
http1 = 81
smtp = 25
smtp2 = 587

In this case, you can import ports.py with simple 
 import ports
 ports.http
80
 

You don't need to define a new file format, just use the python syntax and 
it will work.
The only problem is that the format has to follow the python systax.
So the next wont work
## Ports.py
http = 80
https = 443
http1 = 81
  smtp = 25
smtp2 = 587

 import ports
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File ports.py, line 5
smtp = 25
^
SyntaxError: invalid syntax
 

The same method can be used for making more complex ini files.
I like it very much.
It is because Python is a dynamic language.


Yours sincerely, 
__
Janos Juhasz 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Warehouse system in python

2006-06-20 Thread János Juhász
Dear All,

have seen someone any simple warehouse management framework in python
with receive, issue, inventory ?


Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sockets

2006-05-05 Thread János Juhász
Hi Matt,

the traceroute can be done from the client side or eigther from the server 
side.
The two ones should give the same result with reverse order.
In this case you can do the tracerouting from the server side when the 
client ask it.
I am just thinking about a simple finger deamon, that can do the job for 
you.
You can ask the deamon, with a simple finger request.
Finger.exe is part of th MS system so

c:\finger [EMAIL PROTECTED]

seems to be enough in the login process.


This is the simplest fingerdeamon:

import SocketServer, os, string

class FingerHandler(SocketServer.StreamRequestHandler):
def handle(self):
username = self.rfile.readline(512)
username = string.strip(username)
# Just do your job here
# Do the traceroute, and save the result
 
if __name__ == '__main__':
server = SocketServer.TCPServer( ('', 79), FingerHandler)
server.serve_forever()



Matt wrote ---
Date: Thu, 04 May 2006 09:23:38 -0700
From: Matt Richardson [EMAIL PROTECTED]
Subject: Re: [Tutor] sockets
To: Tutor@python.org
Message-ID: [EMAIL PROTECTED]
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

I need to send some data, 2 strings and a list, to a remote computer.
After thinking about it some last night, it wouldn't be hard to just
send it all as a string and then parse it on the receiving end.

I'm writing a program for work (and for a class project, so no answers!)
that will provide some info on the network location of a laptop.  The
client will gather IP address, MAC address, and a traceroute dump (the
list mentioned above), then send this off to a super simple server that
receives the data and puts it in a database.  We've had a few laptops
'disappear' either through theft or people taking them home to do 'work
from home' or whatever.  Makes annual inventory a huge pain.

Matt




Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Olle-Olla

2006-04-18 Thread János Juhász
Hi All,

Is it possible to replace the print statement with one of mine function ?
Is it any extra reason why print isn't similar to the functions I can make 
with def ?

 def olle(dummy): print 'olle:', dummy
... 
 def olla(dummy): print 'olla:', dummy
... 
 olle('Hopp')
olle: Hopp
 olla('Hopp')
olla: Hopp
 olle = olla
 olle('Hopp')
olla: Hopp
 print = olle
Traceback (  File interactive input, line 1
print = olle
  ^
SyntaxError: invalid syntax


In reality, I would like to replace the print in my PyCrust app with the 
log.write() function.


janos juhasz
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] defined()

2006-04-04 Thread János Juhász
Dear Tim, 
 Dear Alan,

 I can't find the defined() function in python, so I used
'variable name' in dir()

 Is it really missing, or I am just so simple ?

 It is really missing, just as it is for most programming languages.
 Which language(s) do you know that has such a feature?

I should came from Marco Cantu's Delphi 2005 book, that I have read just 
recently.
But I am unable to find it again.

 And why do you consider it so useful that you expect to find
 it in Python?
I don't miss it. It was just a foggy engram, that I couldn't find in the 
help :)

 The main place where I could see such a thing being useful
 would be in dynamically loaded code but then the usual
 approach is to load a dictionary and an 'in' check suffices.

 I'm interested in what use you would make of such a thing?

I just started to make a .leo file, where I wanted to place my scripts.

http://webpages.charter.net/edreamleo/front.html

I just tried to collect all of my scripts (sql, wmi, admin, snmp ...), and 
html references, admin knowledge, passwords for active devices... into one 
place, that can be shared with my colleagues with detailed description 
about the usage and the reasons to use of them. Leo seems to be a very 
good candidate for that.

An sql script seems to be like this.

-
 ScalaDB 

data = Query( Sql )

 Show Data 


In the leo file the  ScalaDB  is simple replaced by the   ScalaDB  
subtree. The script is created dinamically from the texts in the tree. So 
I just wanted to check in the  Show Data  part, if the data is defined 
previously or not.


Yours sincerely, 
__
Janos Juhasz 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] defined()

2006-04-03 Thread János Juhász

Hi All,

I can't find the defined() function
in python, so I used 

'variable name' in dir()

for check if the variable defined.

 name = 'Joe'
 if 'name' in dir():
... print name
... 
Joe

Is it really missing, or I am just
so simple ?



Yours sincerely, 
__
János Juhász 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Automatic software performance meter

2006-03-10 Thread János Juhász
Hi All,

is it any easy way to mesaure a windows software response time from python
 script ?
I think about a small python script that can open a win32 application,
 insert a new order with sendkey, deliver the goods, do other things and
 create a small log file with the different split times.

I would like to controll the time needed for a business procedure instead
 of the ping time  :)



 Yours sincerely,
 __
 János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] saving .csv file as an xl worksheet

2006-03-07 Thread János Juhász
Hi,

last week I had to make a simple solution to convert prn file to excel. It
seems to be very similar.
I just wondered how easy to create an xml file that can be opened with
excel.
It can have functions, autofilters, format descriptions.
It is about 100 times faster to create than on the win32com way.
It is twice bigger than the binary excel, but it can be compressed into the
half size of the compressed binary.
People working with excel can't feel the difference :)

I don't know how can it be opened with StarOffice, but it works well with
excel2003.


##
import os

xmlhead = ?xml version=1.0 encoding=iso-8859-1?
Workbook xmlns=urn:schemas-microsoft-com:office:spreadsheet
 xmlns:o=urn:schemas-microsoft-com:office:office
 xmlns:x=urn:schemas-microsoft-com:office:excel
 xmlns:ss=urn:schemas-microsoft-com:office:spreadsheet
 xmlns:html=http://www.w3.org/TR/REC-html40;
 Worksheet ss:Name=XML XLS test
  Table


xmlsum =Row
Cell ss:Index=3 ss:Formula==SUM(R[-%d]C:R[-1]C)Data
ss:Type=Number/Data/Cell
   /Row


xmlfoot =   /Table
  WorksheetOptions xmlns=urn:schemas-microsoft-com:office:excel
   Unsynced/
   Selected/
  /WorksheetOptions
  AutoFilter x:Range=R1C1:R%dC%d
   xmlns=urn:schemas-microsoft-com:office:excel
  /AutoFilter
 /Worksheet
/Workbook


headrow = ('1st;2nd;3rd')
lines = ('1;2;3', '2;3;4', '3;4;5', '4;5;6')
dest = 'Test.xls'
xml = open(dest, 'wt')
rownum = 1

## Header
xml.write(xmlhead)

## HeadRow
xml.write('Row\n')
for data in headrow.split(';'):
  xml.write(' CellData ss:Type=String%s/Data/Cell\n' %
data)
xml.write('/Row\n')
rownum += 1

## Rows with data
for line in lines:
  colnum = len(line.split(';'))
  xml.write('Row\n')
  for data in line.split(';'):
xml.write(' CellData
ss:Type=Number%s/Data/Cell\n' % data)
  xml.write('/Row\n')
  rownum += 1

## Function with reference
xml.write(xmlsum % (rownum-2))

## Foot
xml.write(xmlfoot % (rownum, colnum))
xml.close()


os.execl(r'c:\Program Files\Microsoft Office\Office10\EXCEL.EXE', dest)
##


Yours sincerely,
__
János Juhász



Date: Tue, 7 Mar 2006 16:38:46 +1100
From: andrew clarke [EMAIL PROTECTED]
Subject: Re: [Tutor] saving .csv file as an xl worksheet
To: tutor@python.org
Message-ID: [EMAIL PROTECTED]
Content-Type: text/plain; charset=us-ascii

On Mon, Mar 06, 2006 at 02:46:36PM +0530, arun wrote:

   Can i save a file with a desired extension??
 for ex:  I have a .csv file (test.csv) and i want to save this file as
 test.xls from a python script.

Just changing the file extension from .csv to .xls won't change the file
format.

OpenOffice 2.0 supports both .csv and .xls file formats and includes
some sort of Python integration.  It may be possible to use that.

Regards
Andrew


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] RDT server for excel

2006-02-27 Thread János Juhász
Hi All,

I would like to make a small RDT Server as COM Server in python that can be
called from excel as =RDT(StockBalance.MyServer,,17)
I'v tried to use google, but with not too much success.
I just would like a simple sample.


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sys.argv

2006-02-13 Thread János Juhász
Hi,

I want to pass args to my python script on XP.
This code
print 'argv[0] %s' % sys.argv[0]
print 'argv[1] %s' % sys.argv[1]
print 'argv[2] %s' % sys.argv[2]

shows this:
argv[0] D:\devel\home\devel\python\db\xlsxml.py
argv[1] K:\IT\admin\test\Flat
argv[2] Files\2006\06.02.2006-293753-gy

but I would see this:
argv[0] D:\devel\home\devel\python\db\xlsxml.py
argv[1] K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy
argv[2] ''


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sys.argv

2006-02-13 Thread János Juhász
Thanks Andre,

The problem came from my wrong script calling.

Python is just fine :)

I corrected it, and I can call it now with


Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\Shell\Flat2Xls\Command]
@=python \D:\\devel\\xlsxml.py\ \%1\


In this case there is a new menu item for the right click popup for any
file that can call my script with the filename as argument.
It works well on my machine with sort and long filenames.
But it uses the old format dos filename on some other PCs.

Is it any way to translate the sort DOS filename to the long NTSF one with
python ?
But it would be fine to set up XP to call my script with the long filename.


Yours sincerely,
__
János Juhász
VELUX Magyarország Fertődi Építőkomponens Kft.
IT Department
Malom Köz 1, H-9431 Fertőd


Telephone direct:  +36 99 537 939
Telephone office:  +36 99 537 920
Office fax:+36 99 537 921
Telephone mobile:+36 30 682 6331
@ [EMAIL PROTECTED]
wwwwww.VELUX.com


Andre Roberge [EMAIL PROTECTED] wrote on 2006.02.13 16:02:39:

 On 2/13/06, János Juhász [EMAIL PROTECTED] wrote:
  Hi,
 
  I want to pass args to my python script on XP.
  This code
  print 'argv[0] %s' % sys.argv[0]
  print 'argv[1] %s' % sys.argv[1]
  print 'argv[2] %s' % sys.argv[2]
 
  shows this:
  argv[0] D:\devel\home\devel\python\db\xlsxml.py
  argv[1] K:\IT\admin\test\Flat
  argv[2] Files\2006\06.02.2006-293753-gy

 Your path has a space in it (between Flat and Files). This is
 probably why it is
 broken as two different arguments.
 André


 
  but I would see this:
  argv[0] D:\devel\home\devel\python\db\xlsxml.py
  argv[1] K:\IT\admin\test\Flat Files\2006\06.02.2006-293753-gy
  argv[2] ''
 
 
  Yours sincerely,
  __
  János Juhász
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Re] Fwd: Strings backwards

2006-01-18 Thread János Juhász
Hi Ryan,

I just extended Adam's code with a speech-to-text recepi from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216.

On 18/01/06, ryan luna [EMAIL PROTECTED] wrote:

 Hello, what i need to do is get user input and then
 print the string backwards ^^ i have no idea how to do
 that,

 print Enter a word and i well tell you how to say it
 backwards

 word = raw_input(Your word: )

 print word

 all that is simple enough im sure printing it out
 backwards is to, just dont know how ^^, thanks for any help.

import sys
from win32com.client import constants
import win32com.client
import string

speaker = win32com.client.Dispatch(SAPI.SpVoice)
print Type word or phrase, then enter.
print Ctrl+Z then enter to exit.

def backword(word):
   l = list(word)
   l.reverse()
   return ''.join(l)

def backsentence(sentence):
   words = sentence.split(' ')
   words = [backword(word) for word in words]
   return ' '.join(words)

while 1:
   try:
  s = raw_input()
  rev = backsentence(s)
  print 'I would say: ', rev
  speaker.Speak(rev)
   except:
  if sys.exc_type is EOFError:
 sys.exit()

It works on my xp :)


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reduce with comprehension

2005-11-21 Thread János Juhász
Hi John,

thanks it.

It is great. I looked for it, but I couldn't made it.
I have tried it with wrong order:
# I have tried it so
[x for x in y for y in a]
[[8], [8], [8], [9], [9], [9]] # that is wrong,

# Instead of that you wrote
[x for y in a for x in y]
[[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]


Yours sincerely,
__
János Juhász


[EMAIL PROTECTED] wrote on 2005.11.21 23:26:03:

 On 21/11/05, János Juhász [EMAIL PROTECTED] wrote:
  I can't imagine how this could be made with list comprehension.
 
   import operator
   a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
   reduce(operator.add, a) # it makes a long list now
  ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9])

 Everything is possible with list comprehensions!

  a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
  [x for y in a for x in y]
 [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]

 We can even go a level deeper!

  [x for z in a for y in z for x in y]
 [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9]

 Just make sure your depth is consistent throughout.

 And remember that that single-line expression is hiding nested FOR loops!

 --
 John.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] split a tuple

2005-11-17 Thread János Juhász
Hi Chris,

Thanks your response.

I have just found another way.

 import math
 l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
 n = 4
 extended = l + ('default',)*int(n - math.fmod(len(l),n))
 [extended[i:i+n] for i in range(0,len(extended),n)]
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]


| Hi,
|
| I couldn't get idea how to make the next thing
|
 n=4 #split into so long parts
 l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split
 [l[i:i+n] for i in range(0,len(l),n)]
| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)]
|
| But I have to make it like this
| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)]
| because i use it later in this
|
 result = [l[i:i+n] for i in range(0,len(l),n)]
 zip(*result)
| [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)]
|
| and as you can see it, the last element is missing here.
|

Since it will always be the last one that is not the correct length; can
you just add another line to extend the length of the last one by the
correct number of default values (that number being the difference between
how many you want and how many you have)?

##
 l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
 n=4
 regrouped = [l[i:i+n] for i in range(0,len(l),n)]
 default = 'default'
 regrouped[-1]=list(regrouped[-1])
 regrouped[-1].extend([default]*(n-len(regrouped[-1])))
 regrouped[-1]=tuple(regrouped[-1])
 regrouped
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')]

 ['a']*3 #so you can see what the rhs multiply does
['a', 'a', 'a']

##

Since tuples cannot be changed, you have to go through the tuple-list
conversion steps. If you can work with a list instead, then these two
steps could be eliminated:

##
 l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead
 regrouped = [l[i:i+n] for i in range(0,len(l),n)]
 regrouped[-1].extend([default]*(n-len(regrouped[-1])))
 regrouped
[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']]

##

/c


Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] split a tuple

2005-11-16 Thread János Juhász
Hi,

I couldn't get idea how to make the next thing

 n=4 #split into so long parts
 l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split
 [l[i:i+n] for i in range(0,len(l),n)]
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)]

But I have to make it like this
[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)]
because i use it later in this

 result = [l[i:i+n] for i in range(0,len(l),n)]
 zip(*result)
[(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)]

and as you can see it, the last element is missing here.



Yours sincerely,
__
János Juhász

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] is there any Python code for spatial tessellation?

2005-10-10 Thread János Juhász


Dear Danny,

take a look to http://public.kitware.com/VTK/
I have seen visualization for voronoi and delaunay in that package.

I have seen also good programming samples mainly in C for calculating
perpedincular and so on at:

 http://www.graphicsgems.org/   


I know it is about 10 years old, but very usable for this topic.

VTK was very good and easy, ( when I downloaded the correct binaries :) )


Yours sincerely,
__
János Juhász


 Message: 7
 Date: Sun, 9 Oct 2005 22:22:29 -0700
 From: Shi Mu [EMAIL PROTECTED]
 Subject: Re: [Tutor] is there any Python code for spatial
 tessellation?
 To: Danny Yoo [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID:
 [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-2022-JP

 There are four points with coordinates:
 2,3;4,9;1,6;3,10.
 How to use Python to draw one perpendicular bisector between (2,3) and
(4,9);
 the other perpendicular bisector between (1,6)?(3,10);
 then, makes the output like:
 l1 a b c
 l2 a b c
 (Note: l indicates the perpendicular bisector with equation ax + by = c.)
 Plus the intersection coordinates of the two perpendicular bisectors:
 x,y


 On 10/8/05, Danny Yoo [EMAIL PROTECTED] wrote:
 
 
  On Sat, 8 Oct 2005, Shi Mu wrote:
 
   is there any Python code for spatial tessellation?
 
  Are you looking for code to generate voronoi diagrams?
 
 http://en.wikipedia.org/wiki/Voronoi_diagram
 
  From initial Google searches, it appears that there is a package called
  Qhull that pepole use to do Voronoi tesselations.
 
 http://www.qhull.org/
 
  and Chris Myers has written a module around Qhull:
 
 http://www.tc.cornell.edu/~myers/PyXL/
 
 
  Otherwise, I don't think we at Tutor can help you that much; you may
want
  to ask on a more math-oriented forum.  Good luck to you!
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OOP fundamentals

2005-09-20 Thread János Juhász
Hi Ed,

last month I have found this beautifull sample about threads and sockets:
  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642

It helped me to a lot to understand how these can be used together on an
OOP way.
It helped me much better, than any hypothetical OOP samples about cars and
wheels, those really usefull just for programming teachers who never made
any real programm, but has to tell something about why OOP is good to
learn.
It was so nice to read and understand a so clean code.
Probably it can help your understanding eighter.
The other place where I feel OOP very natural is using wxPython.

There is another recipe about portscanning with OOP and threading:
  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286240


Yours sincerely,
__
János Juhász



 Message: 5
 Date: Mon, 19 Sep 2005 17:01:30 -0400
 From: Ed Hotchkiss [EMAIL PROTECTED]
 Subject: Re: [Tutor] OOP fundamentals
 To: Danny Yoo [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1

 Thanks Danny! Tommorrow I am off to get Programming for Python, 2nd
 edition and learn everything - all of it, before I even bother with
 Sockets. Afterall, I want python for EVERYTHING not just sockets and inet
 based scripts/applications.
 I realized that I need to take a step back, make port scanner a class
that
 does nothing but really help me learn classes, then insert threading,
then
 once that works, insert the actual sockets into their respective class
def
 etc ... Thanks again ...
 Next time I post, I'll have something either more abstract/theory
question,
 or something that isn't quite so simple!
 Thanks again everyone thats been helping me out especially danny!

 -edward
 -- next part --
 An HTML attachment was scrubbed...
 URL: http://mail.python.
 org/pipermail/tutor/attachments/20050919/41d24153/attachment.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] replace string in a sequentially read stream

2005-09-12 Thread János Juhász
Dear Guys,

I have to run the next regexp change in a stream:

import re

wrongcode = re.compile(r'(.*)b24704T')

f = open('testfile.txt')
while 1:
  sequence = f.read(1024)
  sequence = wrongcode.sub(r'\1b24700T', sequence)
  print sequence

My original solution was to keep the last part of the sequence till the
 next sequence hasn't been arrived


while 1:
  try:
sequence = f.read(1024)
try:
  sequence = prevend + sequence
except:
  pass
sequence = wrongcode.sub(r'\1b24700T', sequence)
prevend = sequence[-20:] # keep the end of the sequence till we
haven't got the complete picture
sequence = sequence[:-20] # the first part was checked
correctly
if not sequence:
  print prevend
  break
print sequence
  except:
break


In the real sample it works on an IP socket.

Have got someone better idea ?
Probably it is better to work with two sequence.



Best regards,
János

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Emulate jetdirect

2005-09-08 Thread János Juhász
Hi All,

I just would make some kind of printer filter for an HP printer, that is
connected to a jetdirect printserver.

The functionality is something like this:
netcat -l -p 9100 | filter.py | netcat 10.36.11.11 9100

I would like to make it as a simple socketserver in python for the port
9100, reading from the socket and sending it to the real jetdirect
printserver over another socket. So it is kind of printer proxy server.
The filter would make some text processing with regular expressions on each
line.

Another wish to use it as an intelligent printer, that can send the
printout to the e-mail address, that is somewhere in the printout. To send
order response via a printing.

netcat -l -p 9100 | senditasemail.py


Can someone show me any example to start it ?


János

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] module with static global

2005-07-12 Thread János Juhász
Dear Guys!

I am using a class for connecting to an sql database via odbc.
It is like this:

import dbi, odbc

class scalaDB:
  def __init__(self):
self.cn =
odbc.odbc('DSN=scalaDB;UID=query;PWD=query;DATABASE=scalaDB')

  def closeDB(self):
self.cn.close()

  def Execute(self, sql):
cr = self.cn.cursor()
cr.execute(sql)
cr.close()

  def Query(self, sql):
try:
  cr = self.cn.cursor()
  cr.execute(sql)
  self.colnames = [field_prop[0] for field_prop in
cr.description]
  self.result = cr.fetchall()
  self.rownum = len(self.result)
  return self.result
except:
  self.colnames = [None]
  self.result = [[None]]
  self.rownum = 0
  return [[None]]

  def QueryValue(self, sql):
try:
  cr = self.cn.cursor()
  cr.execute(sql)
  self.colnames = [field_prop[0] for field_prop in
cr.description]
  self.result = cr.fetchall()
  self.rownum = len(self.result)
  return self.result[0][0]
except:
  self.colnames = [None]
  self.result = None
  self.rownum = 0
  return None

I also have some other classes represented in this database as records. As
the records are in the database, they has to have a scalaDB instance for
running any sql statement on it. Currently I send a scalaDB instance to
every record-based class in the __init__(): proc.

class Component:
  def __init__(self, scalaDB, StockCode, Qty=1, Parent=None):
self.scalaDB = scalaDB
self.StockCode = StockCode
self.Parent = Parent
self.Qty = Qty## Qty in
the BOM
self.Components = self.GetComponents()

  def GetParent(self):
return self.Parent

  def __getattr__(self, name):
if 'SC' in name:k
  value = self.scalaDB.QueryValue(select %s from SC010100
where SC01001 = '%s' % (name, self.StockCode) )
  return value



How have I modify this to use my scalaDB class in this way:

import scalaDB
xy  = scalaDB.Query(sql)



Best regards,
Janos Juhasz

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] max(len(item)) for cols

2005-06-17 Thread János Juhász
Thanks Max,

it is sort, but it gives back the max(len(item)) for the rows

 I have a 2D array:

 [['1', '2 ', '3'], ['longer ', 'longer', 'sort']]



 How can I  get what is the max(len(item)) for the columns ?
 I would like to get a list with the max_col_width values.

 I hope that, it can wrote with some nice list comprehension, but I
 can't do
 that :(

Here is the array:

[['1', '2 ', '3   '],
 [ 'longer','longer','sort']
]

it is len(item) for that:
[[ 1,   2,  3],
 [ 10,10, 4]
]

I would have that is the next:
(10,10,4)
or
[10,10,4]

As I remeneber it is somewhere in numpy, but I am not sure.
I would like to have it simply.


Yours sincerely,
__
Jnos Juhsz




   
 Max Noel   
   
 [EMAIL PROTECTED]
 
To  
   
Jnos Juhsz [EMAIL 
PROTECTED]  
 2005.06.17 13:35   cc  
   
tutor@python.org
   
Subject 
   
Re: [Tutor] max(len(item)) for 
cols

   

   





On Jun 17, 2005, at 11:58, Jnos Juhsz wrote:


 Dear Guys,

 I have a 2D array:

 [['1', '2 ', '3'], ['longer ', 'longer', 'sort']]



 How can I  get what is the max(len(item)) for the columns ?
 I would like to get a list with the max_col_width values.

 I hope that, it can wrote with some nice list comprehension, but I
 can't do
 that :(


  a = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1]]
  max(len(item) for item in a)
4

 If you're running Python 2.3 or lower, add brackets in the last
line:
  max([len(item) for item in a])
4


-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge
a perfect, immortal machine?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] max(len(item)) for cols

2005-06-17 Thread János Juhász
Thanks for jfouhy and Kent!

Both the zip and the recipe are suit for me.
I looked for these.


Yours sincerely,
__
Jnos Juhsz

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] overlap of ranges

2005-05-04 Thread János Juhász
Hi All,

one of my colleague asked me, about how the overlap of two ranges can be
calculated easily.

 a = (24,27) # range1 (endpoint1,endpoint2)
 b = (10,227) # range1 (endpoint1,endpoint2)
 min( max(a), max(b) ) - max( min(a), min(b) )
3

When the result is positive, then the two ranges overlap together.
When the result is negative, then the two ranges doesn't overlap together
and the distance between them is the result multiplied with -1.
As we are using max() and min(), a=(24,27) means the same as a=(27,24).

I haven't seen this calculation method before, and I think it could be
interesting and usefull for coders.


Best regards,
János

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor