Re: Where to find python c-sources

2005-09-29 Thread Max M
Erik Max Francis wrote:
> Tor Erik Sønvisen wrote:
> 
>> I need to browse the socket-module source-code. I believe it's 
>> contained in the file socketmodule.c, but I can't locate this file... 
>> Where should I look?
> 
> The source tarball, available on python.org.  Are people really too lazy 
> to do elementary research on Google?

Don't know, have you checked Google?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New project coming up...stay with Python, or go with a dot net language??? Your thoughts please!

2005-10-04 Thread Max M
spiffo wrote:
> The Main Issue in a nutshell
> 
> I am a corporate developer, working for a single company. Got a new project
> coming up and wondering if I should stay with Python for this new, fairly
> large project, are jump back on the 'safe' M$ bandwagon using a dot net
> language?


Hehe ...

I can run my very first Python program right now in the current version 
of Python. I cannot even find a platform to run my .asp code from that 
same timeframe ... So much for 'safe'!


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python reliability

2005-10-10 Thread Max M
Ville Voipio wrote:
> In article <[EMAIL PROTECTED]>, Paul Rubin wrote:
> 
>>I would say give the app the heaviest stress testing that you can
>>before deploying it, checking carefully for leaks and crashes.  I'd
>>say that regardless of the implementation language.
> 
> Goes without saying. But I would like to be confident (or as
> confident as possible) that all bugs are mine. If I use plain
> C, I think this is the case. Of course, bad memory management
> in the underlying platform will wreak havoc.

Python isn't perfect, but I do believe that is as good as the best of 
the major "standard" systems out there.

You will have *far* greater chances of introducing errors yourself by 
coding in c, than you will encounter in Python.

You can see the bugs fixed in recent versions, and see for yourself 
whether they would have crashed your system. That should be an indicator:

http://www.python.org/2.4.2/NEWS.html


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Windows installer, different versions of Python on Windows

2005-10-10 Thread Max M
I would like to install several copies of Python 2.4.2 on my machine, 
but it doesn't seem to be possible.

If I allready has a version installed, the installer only gives the 
options to:

- change python 2.4.2
- repair python 2.4.2
- remove python 2.4.2

I would like to install different versions of Zope 3, and since it is 
installed under a specific python version, the simplest solution would 
be to install several Python versions, and install a different zope3 
version under each python install.

Have I misunderstood something here?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> I must be missing something but what is the proper way to do a function 
> using such arguments ?

> - ability to take an unspecified number of "positional arguments"

You should probably pass a sequence to the method instead. You can do it 
the other way, but it's poor coding style in most cases.


> - ability to take optional named arguments that follows the first arguments

Setting the default value to a value that cannot exist as an argument is 
the normal way. Eg. None.

def fn(vals, cmp=None)


> - raise appropriate errors if I use the wrong named arguments

def fn(*values, cmp=None):
 if cmp is None:
 raise TypeError, "'%s' is an invalid keyword argument for this 
function" % key


If you insist on doing it the other way:

FN_LEGAL_ARGS = set( ('cmp',) )

def fn(*values, **options):
 for key in options.keys():
 if not key in FN_LEGAL_ARGS:
 raise TypeError, "'%s' is an invalid keyword argument for 
this function" % key


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> Max M wrote:

> So what you're saying is that instead of:
> 
> def fn(*values, **options):
> 
> I should use:
> 
> def fn(values, cmp=cmp):
> 
> in this specific case?
> 
> and then instead of:
> 
> fn(1, 2, 3, cmp=...)
> 
> this:
> 
> fn([1, 2, 3], cmp=...)

Precisely. Sometimes you need different interfaces for a method. In that 
case it is fine.

But if you are just doing it instead of passing sequences, you are just 
(ab)using the * and ** operators.

The method definition, like any python code, is made for humans not 
machines. The more obvious you can make the function definition, the 
happier anyone will be.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-23 Thread Max M
Mike Meyer wrote:

> There were studies done in the 70s that showed that programmers
> produced the same number of debugged lines of code a day no matter
> what language they used. So a language that lets you build the same
> program with fewer lines of code will let you build the program in
> less time.

In my experience the LOC count is *far* less significant than the levels 
of indirections.

Eg. how many levels of abstraction do I have to understand to follow a 
traceback, or to understand what a method relly does in a complex system.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending email in utf-8?

2005-11-08 Thread Max M
morphex wrote:
> That works, kinda.  I get strange characters now like this
> 
> """
> Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST)
> Message-Id: <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED], [EMAIL PROTECTED]
> From: [EMAIL PROTECTED]
> Subject:  Order confirmation
> Content-Type: text/plain; charset="utf-8"
> X-Bogosity: No, tests=bogofilter, spamicity=0.00, version=0.92.8
> 
> Thank you for your order, it is copied here for your convenience, and
> we will process it shortly.
> 
> Name:  ø
> Phone: ø
> Email:  [EMAIL PROTECTED]
> Comments:  asdf
> """
> 
> but at least it doesn't raise any errors.
> 

This is a method I have clipped from one of my projects. It should 
pretty much cover everything you would want to do while sending mails.


 def Workgroup_mailFormAction(self, to=None, cc=None, bcc=None, 
inReplyTo=None,
  subject=None, body='', 
attachments=None, mfrom=None,
  REQUEST=None):
 """
 Sends a message. Many of the input parameters are not currently 
used,
 but can be used for skinning the functionlity.
 """
 site_encoding = self._site_encoding()
 ##
 # Create the message
 msg = Message()
 msg.set_payload(body, site_encoding)
 #
 # if attachment, convert to multipart
 # file fields are posted even if empty, so we need to remove 
those :-s
 if attachments is None:
 attachments = []
 attachments = [a for a in attachments if a]
 if attachments:
 mimeMsg = MIMEMultipart()
 mimeMsg.attach(msg)
 for attachment in attachments:
 # Add the attachment
 tmp = email.message_from_string(str(attachment.headers))
 filename = tmp.get_param('filename', 'Attachment', 
'Content-Disposition')
 # clean up IE paths
 filename = filename[max(filename.rfind('/'),
 filename.rfind('\\'),
 filename.rfind(':')
)+1:]
 contentType = tmp['Content-Type']
 attach_part = Message()
 attach_part.add_header('Content-Type', contentType, 
name=filename)
 attach_part.add_header('Content-Disposition', 
'attachment', filename=filename)
 attach_part.set_payload(attachment.read())
 Encoders.encode_base64(attach_part)
 mimeMsg.attach(attach_part)
 msg = mimeMsg
 
 # set headers on message
 
 if to is None:
 to = []
 if mfrom:
 to.append(mfrom)
 msg['From'] = mfrom
 msg['Reply-To'] = mfrom
 to = ','.join(to)
 if to: msg['To'] = to
 
 if cc is None:
 cc = []
 cc = ','.join(cc)
 if cc: msg['Cc'] = cc
 
 if bcc is None:
 bcc = []
 bcc = ','.join(bcc)
 if bcc: msg['Bcc'] = bcc
 
 msg['Date'] = self.ZopeTime().rfc822() # needed by some servers
 if inReplyTo:
 msg['In-Reply-To'] = inReplyTo
 msg['Subject'] = Header(subject, site_encoding)
 ##
 # Send the message
 SMTPserver = self._mailhost()
 success = 0
 try:
 cleaner = lambda adresses: [adress.strip() for adress in 
adresses.split(',') if adress.strip()]
 all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc)
 all_receivers = list(set(all_receivers))
 if all_receivers: # only send if any recipients
 self._mailhost().send(str(msg), mto=all_receivers, 
mfrom=mfrom)
 success = 1
 except:
 pass


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: append to non-existing list

2005-11-09 Thread Max M
Yves Glodt wrote:
> bruno at modulix wrote:
> 
>> Yves Glodt wrote:
>>
>>> Hello,
>>>
>>> if I do this:
>>>
>>> for row in sqlsth:
>>> pkcolumns.append(row[0].strip())
>>> etc
>>>
>>>
>>> without a prior:
>>>
>>> pkcolumns = [];
>>>
>>>
>>> I get this error on first iteration:
>>> UnboundLocalError: local variable 'pkcolums' referenced before 
>>> assignment
>>>
>>>
>>> I guess that's normal as it's the way python works...?!?


Well you could do something like this. (Untested and unrecommended)

 self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

 pkcolumns = []
 pkcolumns .append(row[0].strip())

to be nicer ;-)

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Midi Package: writing events non-chronologically

2005-11-24 Thread Max M

tim wrote:
Someone using Python Midi Package from 
http://www.mxm.dk/products/public/ lately?


I want to do the following :
write some note events in a midi file
then after doing that, put some controllers at the beginning of the 
midifile
(because I want to be able to make those dependant on what notes were 
just written)


def midctrls():
   global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, 
usednotes, n

   midi.reset_time()  #seems to do nothing
   for cha in range(16):
   if cha==1:
   midi.abs_time=0   #seems to do nothing
   midi._relative_time = 0   #seems to do nothing, but I can 
imagine why

   midi._absolute_time = 0   #seems to do nothing
   midi.update_time(new_time=0, relative=0)  #although I give 
the variable relative=0 it seems to be relative ?

   midi.continuous_controller(cha, 0, 122)
(snip)

With this code I want a controller number 0 with value 122 to be written 
at the beginning of my midifile.

It is written at the end, how I move the writing position to the beginning?




You should make a wrapper around the library that handles the midi 
events in a data structure.


When your musical structure is then is complete, you use the midi 
library to write it to disk.


I have attached a simple example here.

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
# event classes. Only used internally by notes2midi
class NoteOn:

def __init__(self, time=0, pitch=64, velocity=64):
self.time = time
self.pitch = pitch
self.velocity = velocity

def __str__(self):
r = []
a = r.append
a('NoteOn')
a('time %s' % self.time)
a('pitch %s' % self.pitch)
a('velocity %s' % self.velocity)
return '\n'.join(r)

def render(self, channel, mididevice):
"Writes the event to a midi stream"
mididevice.note_on(channel=channel, note=self.pitch, 
velocity=self.velocity)



class NoteOff:

def __init__(self, time=0, pitch=64, velocity=64):
self.time = time
self.pitch = pitch
self.velocity = velocity

def __str__(self):
r = []
a = r.append
a('NoteOff')
a('time %s' % self.time)
a('pitch %s' % self.pitch)
a('velocity %s' % self.velocity)
return '\n'.join(r)

def render(self, channel, mididevice):
"Writes the event to a midi stream"
mididevice.note_off(channel=channel, note=self.pitch, 
velocity=self.velocity)




def notes2midi(notes, midi):
"Turns a list of notes into a midi stream"
# notes have absolute time values!!!

# first turn notes into events (split into note-on / note-off)
events = []
for note in notes:
on_event = NoteOn(note.time, note.pitch, note.velocity)
events.append(on_event)
off_event = NoteOff(note.time+note.duration, note.pitch, note.velocity)
events.append(off_event)
# sort them in order of time
events.sort(lambda x,y: cmp(x.time, y.time))

# midi device writing
# non optional midi framework
midi.header()
midi.start_of_track()
midi.reset_time()
absolute_time = 0
for event in events:
delta_time = event.time - absolute_time
absolute_time = event.time
# write the data
midi.update_time(delta_time)
event.render(0, midi)
midi.end_of_track()
# non optional midi framework
midi.update_time(0)
midi.end_of_track()

midi.eof()


if __name__ == '__main__':

from Pattern import Note

# a short example using notes, with no limits to number of simultaneous 
voices
# creates a list of ascending notes
track = [
Note(time=24*i, pitch=64+i, velocity=127, duration=24)
for i in range(16)
]


##
# write the notes to the file

from midi.MidiOutFile import MidiOutFile

out_file = 'note-test.mid'
midi = MidiOutFile(out_file)
notes2midi(track, midi)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Calling Function Without Parentheses!

2005-01-02 Thread Max M
Kamilche wrote:
What a debug nightmare! I just spent HOURS running my script through
the debugger, sprinkling in log statements, and the like, tracking down
my problem.
I called a function without the ending parentheses. I sure do WISH
Python would trap it when I try to do the following:
MyFunc

Actually you want use a method as an ordinary variable without calling 
it in many cases. It is often used in a dynamic language.

A simple example is:
result = []
a = result.append
if something:
 a('some result')
elif something_else:
 a('another result')
else:
 a('default result')
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: csh to Python

2005-01-04 Thread Max M
Nader Emami wrote:
Hello,
I am new in Python world, and would like to begin with
translate a csh file to a python script. Could somebody give
me an advise (documentation or web-site) where I can do that.

You are probably interrested in the os 6 os.path modules.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Max M
[EMAIL PROTECTED] wrote:
uhm ... then there is a misprint in the discussion of the recipe;
BTW what's the difference between .encode and .decode ?
(yes, I have been living in happy ASCII-land until now ... ;)

# -*- coding: latin-1 -*-
# here i make a unicode string
unicode_file = u'Some danish characters æøå' #.encode('hex')
print type(unicode_file)
print repr(unicode_file)
print ''
# I can convert this unicode string to an ordinary string.
# because æøå are in the latin-1 charmap it can be understood as
# a latin-1 string
# the æøå characters even has the same value in both
latin1_file = unicode_file.encode('latin-1')
print type(latin1_file)
print repr(latin1_file)
print latin1_file
print ''
## I can *not* convert it to ascii
#ascii_file = unicode_file.encode('ascii')
#print ''
# I can also convert it to utf-8
utf8_file = unicode_file.encode('utf-8')
print type(utf8_file)
print repr(utf8_file)
print utf8_file
print ''
#utf8_file is now an ordinary string. again it can help to think of it 
as a file
#format.
#
#I can convert this file/string back to unicode again by using the 
decode method.
#It tells python to decode this "file format" as utf-8 when it loads it 
onto a
#unicode string. And we are back where we started

unicode_file = utf8_file.decode('utf-8')
print type(unicode_file)
print repr(unicode_file)
print ''
# So basically you can encode a unicode string into a special 
string/file format
# and you can decode a string from a special string/file format back 
into unicode.

###

u'Some danish characters \xe6\xf8\xe5'

'Some danish characters \xe6\xf8\xe5'
Some danish characters æøå

'Some danish characters \xc3\xa6\xc3\xb8\xc3\xa5'
Some danish characters æøå

u'Some danish characters \xe6\xf8\xe5'


--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Max M
Thomas Heller wrote:
It seems also the error messages aren't too helpful:
"ä".encode("latin-1")
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal 
not in range(128)
Hm, why does the 'encode' call complain about decoding?
Because it tries to print it out to your console and fail. While writing 
to the console it tries to convert to ascii.

Beside, you should write:
u"ä".encode("latin-1") to get a latin-1 encoded string.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-05 Thread Max M
Carl Banks wrote:
Also, note that there are some encodings unrelated to Unicode.  For
example, try this:
. >>> "abcd".encode("base64")
This is an encoding between two byte strings.
Yes. This can be especially nice when you need to use restricted charsets.
I needed to use unicode objects as Zope ids. But Zope only accepts a 
subset of ascii as ids.

So I used:
hex_id = u'INBOX'.encode('utf-8').encode('hex')
>>494e424f58
And I can get the unicode representation back with:
unicode_id = id.decode('hex').decode('utf-8')
>>u'INBOX'
Tn that case id.decode('hex') doesn't return a unicode, but a utf-8 
encoded string.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: smtp question

2005-01-05 Thread Max M
Philippe C. Martin wrote:
Hi,
I am testing the smtp module and have the following question:
in the code below (taken from net sample) prior to adding the "Subject:"
field, the email client found the "From" and the "To". Without the
"Subject:" field on I get this:
Email client = Evolution: the "From" field is blank
Email client = KMail: the "To" field is blank
Any clue ?
It' very easy to create email messages with the email module.
>>> from email.Message import Message
>>> fromaddr = '[EMAIL PROTECTED]'
>>> to = '[EMAIL PROTECTED]'
>>> msg = Message()
>>> msg['Subject'] = 'From Python'
>>> msg['From'] = fromaddr
>>> msg['To'] = to
>>> body = "This is the message content"
>>> msg.set_payload(body)
Thats all. Though some smtp servers needs a Date header too, to work.
>>> from time import gmtime, strftime
>>> msg['Date'] = strftime("%a, %d %b %Y %H:%M:%S +", gmtime())
Sending the message via the smtp module is even simpler.
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail(fromaddr, [to], msg.as_string())
>>> server.quit()
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Returning same type as self for arithmetic in subclasses

2005-01-07 Thread Max M
# -*- coding: latin-1 -*-
"""
I subclass datetime and timedelta
>>> dt = myDatetime(1970,1,1)
>>> type(dt)

>>> td = myTimedelta(hours=1)
>>> type(td)

But when I do arithmetic with these classes, they return datetime and 
timedelta,
where I want them to return myDatetime and myTimedelta

>>> new_time = dt + td
>>> new_time
datetime.datetime(1970, 1, 1, 1, 0)
>>> type(new_time)

So I wondered if there was a simlpler way to coerce the result into my 
desired
types rather than overwriting the __add__, __sub__ etc. methods?

"""
from datetime import datetime, timedelta
class myDatetime(datetime):
pass
class myTimedelta(timedelta):
pass
if __name__ == "__main__":
import os.path, doctest, dtime
# import and test this file
doctest.testmod(dtime)

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Returning same type as self for arithmetic in subclasses

2005-01-08 Thread Max M
Tim Peters wrote:
Yes, and all builtin Python types work that way.  For example,
int.__add__ or float.__add__ applied to a subclass of int or float
will return an int or float; similarly for a subclass of str.  This
was Guido's decision...
I will not discuss it with him. He is usually right :-s

Generally speaking, no.  But I'm sure someone will torture you with a
framework that purports to make it easy .
Apparently not... But here is my solution.
If anybody is interrested. It should also be obvious what I am working on.
Btw. I really love doctests ... Unittests are a nice idea. But doctest 
is a really practical solution.

###
class vDatetime(datetime):
"""
A subclass of datetime, that renders itself in the iCalendar datetime
format.
>>> dt = vDatetime(1970, 1,1, 12, 30, 0)
>>> str(dt)
'19700101T123000'
>>> dt2 = vDatetime(1970, 1,1, 0, 0, 0)
>>> str(dt - dt2)
'PT12H30M'
Adding is not allowed
>>> dt + dt2
Traceback (most recent call last):
...
AttributeError: 'NotImplementedType' object has no attribute 'days'
"""
def __init__(self, *args, **kwargs):
datetime.__init__(self, *args, **kwargs)
self.params = Params()
def __add__(self, other):
return self._to_vdatetime(datetime.__add__(self, other))
def __sub__(self, other):
return self._to_vdatetime(datetime.__sub__(self, other))
def _to_vdatetime(self, result):
if hasattr(result, 'timetuple'):
return vDatetime(*result.timetuple()[:6])
return vDuration(result.days, result.seconds)
def fromstring(st):
"Class method that parses"
try:
timetuple = map(int, ((
st[:4], # year
st[4:6],# month
st[6:8],# day
st[9:11],# hour
st[11:13],# minute
st[13:15],# second
)))
except:
raise ValueError, 'Wrong format'
return vDatetime(*timetuple)
fromstring = staticmethod(fromstring)
def __str__(self):
return self.strftime("%Y%m%dT%H%M%S")

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Another look at language comparisons

2005-01-08 Thread Max M
Jan Dries wrote:
[EMAIL PROTECTED] wrote:
And there is hope for Python, as Guido has recently been seen with a 
beard :-)
http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg
LOL, he is working on linux, isn't he?
So it was about bloody time.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Weekly Python Patch/Bug Summary

2005-01-08 Thread Max M
Kurt B. Kaiser wrote:
Remove witty comment in pydoc.py  (2005-01-01)
CLOSED http://python.org/sf/1094007  opened by  Reinhold Birkenfeld
This is not a joke? :-)
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


oddities in the datetime module

2005-01-14 Thread Max M
# -*- coding: latin-1 -*-
"""
I am currently using the datetime package, but I find that the design is 
oddly
asymmetric. I would like to know why. Or perhaps I have misunderstood 
how it should be used?

I can make a datetime easily enough
>>> datetime(2005, 1, 1)
datetime.datetime(2005, 1, 1, 0, 0)
What I find odd is that I cannot make a new datetime object from the 
timetuple()
like this:

>>> d1 = datetime(2005, 1, 1, 12, 13, 10)
>>> d2 = datetime(*d1.timetuple())
Traceback (most recent call last):
...
TypeError: function takes at most 8 arguments (9 given)
>>> d1.timetuple()
(2005, 1, 1, 12, 13, 10, 5, 1, -1)
Because if I subclass datetime, I often need to convert between my 
subclass and
the built in datetime module. But there is no direct way to do it.

Instead I have to do it in a somewhat more clunky way:
>>> datetime(* (d1.timetuple()[:6] + (0, d1.tzinfo)))
datetime.datetime(2005, 1, 1, 12, 13, 10)
if I want to convert a date to a datetime it is easy, even though I 
still have
to truncate the timetuple.

>>> d = date(2005, 1, 1)
>>> datetime(*d.timetuple()[:6])
datetime.datetime(2005, 1, 1, 0, 0)
The other way around is also easy.
>>> dt = datetime(2005, 1, 1, 12, 0, 0)
>>> date(*dt.timetuple()[:3])
datetime.date(2005, 1, 1)
But it's a clunky design that I have to do it that way.
I think it would be nice if date and datetime at least had a pair of
datetimetuple() and from_datetimetuple() methods that could be used for 
easily
converting between datetime types. Like the ones I have made below.

That would make them a lot more symmetric.
>>> datetimetuple = (2005,1,1,12,0,0,0,None)
>>> datetime2.from_datetimetuple(datetimetuple)
datetime2(2005, 1, 1, 12, 0)
>>> dtt = datetime2(2005,1, 1).datetimetuple()
>>> dtt
(2005, 1, 1, 0, 0, 0, 0, None)
>>> d2 = date2.from_datetimetuple(dtt)
>>> d2
date2(2005, 1, 1)
>>> datetime2.from_datetimetuple(d2.datetimetuple())
datetime2(2005, 1, 1, 0, 0)
"""
from datetime import datetime, date
class datetime2(datetime):
def datetimetuple(self):
return self.timetuple()[:6] + (0, self.tzinfo)
def from_datetimetuple(dt_tuple):
return datetime2(*dt_tuple)
from_datetimetuple = staticmethod(from_datetimetuple)
class date2(date):
def datetimetuple(self):
return self.timetuple()[:6] + (0, None)
def from_datetimetuple(dt_tuple):
return date2(*dt_tuple[:3])
from_datetimetuple = staticmethod(from_datetimetuple)

#from datetime import datetime
#
#ical = Calendar()
#print ical.ical()
if __name__ == "__main__":
import os.path, doctest, x
# import and test this file
doctest.testmod(x)
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: oddities in the datetime module

2005-01-14 Thread Max M
Serge Orlov wrote:
Max M wrote:

Yes, you did. datetime.timetuple is those who want *time module* format, you should use datetime.data, datetime.time, datetime.year 
and so on...

As they say, if the only tool you have is timetuple, everything looks like tuple 

Try this:
dt = datetime(2005, 1, 1, 12, 0, 0)
dt.date()
datetime.date(2005, 1, 1)
This doesn't solve it. I don't think you understand my issue.
First of, it should be possible to easily convert between the datetime 
objects.

And eg. the date object doesn't have a datetime() method. Which it could 
easily have. Neither does time. They could have. But I don't think that 
is the way to solve it.


It is a problem if you make a subclass of datetime. Often you will ned 
to make datetime arithmetics with the new class.

Like: datetime_subclass_1 + datetime_subclass_2
The result of that is a plain datetime
In that case you will rather want your own subclass returned. But 
subclasses of datetime returns datetime objects. Not the subclass.

So to do an add of your own objects you must convert the output to your 
own class "manually"

class my_datetime(datetime):
def __add__(self, other):
result = datetime.__add__(self, other)
return my_datetime(result.timetuple()[:6])
datetime(), time() etc. methods will not help with this.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] iCalendar package 0.9

2005-01-17 Thread Max M
I have written a package that can parse and generate files according to 
RFC 2445 (iCalender). That should be any file ending with .ics :-)

It is not quite polished yet, but fully functional, and choke full of 
doctest.

It does support the full spec and all datatypes and parameter values.
The Api is pretty stable, and will probably not change much.
I would like anybody interrested to give it a test drive before I finish 
it off and make it a 1.0.

http://www.mxm.dk/products/public/ical/
Any feedback would be welcome.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] iCalendar package 0.9

2005-01-18 Thread Max M
Roger Binns wrote:
"Max M" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
http://www.mxm.dk/products/public/ical/
Any feedback would be welcome.

How well do you cope with the crud that real programs generate?  Does it work
with the different dialects uses out there?  Can it at least identify them?

It depends on how badly the data is screwed up. But generally it should 
be able to work on incorrect implementations.

It doesn't care of the spelling of property and parameter names. Though 
type conversions will need to be done slightly more manual.

If something like 'dtstart' is misspelled it will not return a datetime
>>> cal.decoded('datestart')
But if you know that it is misspelled you can get it, and convert it 
manually like:

>>> from PropertyValues import vDDDType
>>> vDDDType.from_ical(cal['datestart'])
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: find isset() php function equivalent in python

2005-02-01 Thread Max M
Ola Natvig wrote:
Olivier Noblanc ATOUSOFT wrote:
Hello
What is the equivalent function of php isset() in python
try:
if variable:
# isset
pass
except NameError:
# not set
pass

you could use:
>>> 'variable' in vars()
But be aware that it is bad bad practice to do it like that.
If you need variables that you don't know that name of, you should put 
them in a dictionary. They are made for that exact purpose.

>>> unkown_vars = {}
>>> unkown_vars['variable'] = 42
>>> 'variable' in unkown_vars
True
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Max M
Nico Grubert wrote:
If it's not to learn, and you simply want it to work, try out this library:
http://zope.org/Members/chrisw/StripOGram/readme
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Filenames with non-Ascii-Characters

2005-02-02 Thread Max M
Marian Aldenhövel wrote:
 > If you're printing to the console, modern Pythons will try to guess the
 > console's encoding (e.g. cp850).
But it seems to have quessed wrong. I don't blame it, I would not know of
any way to reliably figure out this setting.
Have you set the coding cookie in your file?
Try adding this as the first or second line.
# -*- coding: cp850 -*-
Python will then know how your file is encoded
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Boss wants me to program

2005-06-28 Thread Max M
phil wrote:

> You would be wise, if you choose Python to choose Tkinter or WxWindows
> and learn the properties of a radio button and how to trigger events.
> Writing simple GUIs is not that hard.  Then after you know what is
> going on behind the scenes, a BOA Constructor will not be as
> mysterious or dangerous.

I agree. The language is more important than the gui. It is not very 
hard to make good applikations in eg. Tkinter, and you will understand 
evey part of it.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modules for inclusion in standard library?

2005-07-01 Thread Max M
Reinhold Birkenfeld wrote:
> Hello,
>
> Do you have any other good and valued Python modules that you would think are
> bug-free, mature (that includes a long release distance) and useful enough to
> be granted a place in the stdlib?
> 
> For my part, ctypes seems like a suggestion to start with.

ctypes certainly. Even though it can crash Python. People using ctypes 
would be aware of this.

Another good bet is BeautifulSoup, which is absolutely great for 
scraping content from webpages.

http://crummy.com/software/BeautifulSoup/index.html


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What are the other options against Zope?

2005-07-04 Thread Max M
phil wrote:
> Peter Hansen wrote:

> Now understand, I know what very well what Python, Apache, PhP,
> MySQL, IE and javascript do.  I just don't know what Zope
> does.
> 
> And if the answer is going contain phrases like "brings together"
> or "sits on top of", don't bother. :-)


It's an object oriented database, with a structure that is similar to 
files and directories in an ordinary OS.

But it is a lot smarter, because the files and directories are actually 
objects with different attributes and parameters.

The methods on these objects can then be called eg. from a web browser 
with different parameters. But you can also use other protocols than 
http like dav, ftp etc.

This is a very effective way to build web applications, and does not 
need sql-object remapping as normal web apps does.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: f*cking re module

2005-07-04 Thread Max M
jwaixs wrote:
> arg... I've lost 1.5 hours of my precious time to try letting re work
> correcty. There's really not a single good re tutorial or documentation
> I could found! There are only reference, and if you don't know how a
> module work you won't learn it from a reference!

If you want to try out re interactively you could use:

\Tools\Scripts\redemo.py


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mail sending using telnet in python

2005-07-08 Thread Max M
praba kar wrote:
> Dear All,
>   Normally we can send mail using
> telnet in linux. In the following way

> Is it possible to run same thing same manner
> in python?  If possible kindly help me with
> specimen code.  Actually I gone through
> telnetlib module documentation but I cann't
> get solution for it.

Why not just use the smtp module? It's a tad easier.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unix diff command under Window.

2005-08-25 Thread Max M
TonyHa wrote:
> Hello,
> 
> Does any one have using Python to write a Unix "diff" command for
> Window?


I generally just us the diff built into tortoiseSVN. That way it's only 
a rightclick away.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyDev 0.9.8 released

2005-08-30 Thread Max M
Fabio Zadrozny wrote:
> Hi All,
> 
> PyDev - Python IDE (Python Development Enviroment for Eclipse) version 
> 0.9.8 has just been released.


I read this, and thought it was time to check out both Eclipse, end the 
pydev plugin.

I got it all installed, along with a subversion plugin for eclipse, and 
it actually seems like a very sweet combo.

I was afraid that a Java based editor would be sluggish. But it doesn't 
seem so.

There are a few nice features too with a file navigator, refactoring, 
code folding and more.

So I have decided to give it a try. But before commiting to it, I just 
wondered what experiences other users might have when using it for 
production. Being that my text editing environment is my bread and butter.

Is it stable/effective etc?

Anybody cares to share?

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyDev 0.9.8 released

2005-08-30 Thread Max M
Fabio Zadrozny wrote:
> Hi Max,
> 
> I may be a little (or maybe a lot) biased for it (as I'm its 
> maintainer), but as I do 'eat my own dogfood', I though I might share it 
> with you...

Enthusiasm doesn't disqualify ;-)


> At my company, everybody that programs with python switched to pydev. 
> Most people used 'highly customized' text-editors before pydev, as the 
> company does not enforce one ambient for all... still, everybody changed 
> to pydev, coming from vi, scintilla, komodo... and we have some really 
> big projects (my current ambient has about 400 python modules, all 
> managed in pydev). Also, there are no current bug reports for any 
> instability in pydev.


Ok. I am starting a new product for Plone tomorrow, that should take 
about a week to finish. I will try switching cold-turkey to pydev and 
see how it goes.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: brain cramp: emulating cgi.FieldStorage

2005-09-15 Thread Max M
Chris Curvey wrote:
> I can't be the first person to want to do this, but I also can't seem
> to find a solution.  (Perhaps my Google skills are poor today.)  How
> can I emulate cgi.FieldStorage() for my unit tests so that I don't have
> to put a web server in the way?
> 
> what I'd like to do is something like
> 
> fs = cgi.FieldStorage()
> fs["foo"] = "bar"
> functionToBeTested(fs)
> 
> Any hints/leads/suggestions?


Can't you just pass the FieldStorage some dummy data to parse?

It looks pretty simple.

class FieldStorage:

 def __init__(self, fp=None, headers=None, outerboundary="",
  environ=os.environ, keep_blank_values=0, 
strict_parsing=0):
 """Constructor.  Read multipart/* until last part.

 Arguments, all optional:

 fp  : file pointer; default: sys.stdin
 (not used when the request method is GET)

 headers : header dictionary-like object; default:
 taken from environ as per CGI spec

 outerboundary   : terminating multipart boundary
 (for internal use only)

 environ : environment dictionary; default: os.environ

 keep_blank_values: flag indicating whether blank values in
 URL encoded forms should be treated as blank strings.
 A true value indicates that blanks should be retained as
 blank strings.  The default false value indicates that
 blank values are to be ignored and treated as if they were
 not included.

 strict_parsing: flag indicating what to do with parsing errors.
 If false (the default), errors are silently ignored.
 If true, errors raise a ValueError exception.

 """


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE, widget library

2005-09-16 Thread Max M
[EMAIL PROTECTED] wrote:
> I like to use Eclipse with the Pydev plugin which is quite good and is
> cross-platform.


I have used those on Windows for about 3 weeks now, and I must say that 
the switch has been allmost completely painless.

I have only good things to say about it.

I can see that my Java process takes up about 80 MBytes, so it is a bit 
of a hog. But who cares... isn't 1 GB getting to be the standard these days?

I have a 1 GHz machine, and the IDE is plenty fast. It has a few 
idiosyncrasies that needs to be learned, but I guess that Emacs has more ...


Good job on pydev!

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary to file

2005-09-16 Thread Max M
Enrique Palomo Jiménez wrote:
> Hi all,
> 
> I'm writing an application who needs to handle a lot of information of 
> several files.
> So, i think the better way is design a batch process to catch that 
> information in a dictionary and write it in a file.
> So, after that when a user wants to retrieve something, only with an execfile 
> i'll have all the information avaiable.
> 
> Creating the file with pythonic syntax will be a hard job so,
> 
> is there some module to do that?
> is there a better way?


You can easily pickle a dictionary and save that to a file.

http://docs.python.org/lib/module-pickle.html

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C#3.0 and lambdas

2005-09-19 Thread Max M
Steven D'Aprano wrote:
> On Mon, 19 Sep 2005 10:31:48 +0200, Fredrik Lundh wrote:
> 
> How many items should you pass in the tuple? If it takes variable
> arguments, then that works, but if you always expect a fixed number, then
> 
> def func((x, y))
> 
> is more explicit.
> 
> The only problem I have is that once you unroll the tuple like that, it is
> hardly necessary to pass the argument as a tuple. Why not just pass x and
> y as two arguments?
> 
> def func(x, y)


why not just pass the tuple as arguments then?

def func(*(x, y))

or as it would normally look:

def func(*arg)

That should work just as well for those cases.



-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert from unicode to int

2005-09-22 Thread Max M
Tor Erik Sønvisen wrote:
> Hi
> 
> Is there any simpler way to convert a unicode numeric to an int than:
> 
> int(u'1024'.encode('ascii'))


why doesn't:

 int(u'104')

work for you?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python as capable as Perl for sysadmin work?

2005-02-08 Thread Max M
Jeff Epler wrote:
No.
Unlike Perl, Python implements only a *finite turning machine* model of
computation.  An easy way to see this limitation is in the following
code:
>>> 1.0 / 10.0
0.10001
In an infinite Turning machine, there would be an unbounded number of
zeros before the second 1, giving the exact result, not a numeric
approximation.
Another thing is that in Perl it turns left, while in Python it turns 
right. hence the .rfind() string method.


Well, if you ever
have to threaten Python, just keep in mind that '... or die' just plain
won't work.  You have to suggest that it 'try ... except', which is
really offensive.  If I want to beg my computer to run programs, I know
where to find Intercal with its "PLEASE" and "DO PLEASE" constructions.
Wasn't there talk about a "try harder" recently?
try:
statement
tryharder:
statement
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Big development in the GUI realm

2005-02-11 Thread Max M
Josef Dalcolmo wrote:
You can distribute GPL'ed code in binary form, you just have to make
the sources available as well.  And, yes I would use this as a test:
if your program needs gpl-ed code for some of it's functionality, you
have to licence your program according to the GPL - unless you
distribute the GPL'ed parts separately and your program is still
basically functioning without the GPL'ed code.
Besides this, why not putting your code under the GPL? 

GPL is not suitable for all kinds of software. It's nice if you are 
sharing code with others, but if you are developing something like a 
desktop application that you want to sell for money, using the GPL is a 
bad idea.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't join() call str() on its arguments?

2005-02-17 Thread Max M
Nick Craig-Wood wrote:
Nick Vargish <[EMAIL PROTECTED]> wrote:

Why not have another method to do this?  I propose joinany which will
join any type of object together, not just strings
>>> l = [1,2,3,'four']
>>> ','.join(map(str, l))
'1,2,3,four'
Is this really that hard to do, that you want it in the library?
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: tiff via email-module

2005-02-17 Thread Max M
Arenz, Ralph wrote:
hi all,
my problem is to get a tiff-file-attachment out of an email sent by a
fax-server.
When i try this with "get_payload(decode='True')" i get additional 
informations, looks like binary-mixed header-information, enveloping the 
tiff-data. 
get_payload(decode=1) returns the decoded data. eg. the "binary" value 
of a file attachement.

If you get additional information there is most likely something wrong 
with your message, or you are not traversing it correctly.

You should do something like::
# untested
def getAttachments(message):
"Returns attachments from message"
maintype = message.get_type()
if maintype == 'application/octet-stream' :
return [message.get_payload(decode=1)]
if message.is_multipart():
attachments = []
for part in message.walk():
attachments.append(part.get_payload(decode=1))
return attachments
return []
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Copy functio in imaplib

2005-02-22 Thread Max M
Raghul wrote:
What is message_set in the python documentation for copy in imaplib? Is
they referring message set  to the particular mail message in my inbox
or something else.
copy(   message_set, new_mailbox)
Copy message_set messages onto end of new_mailbox.
A sequence of numbers encoded as a string. In one of the forms:
'1,2,3,4' or '1:4'
The numbers can be either message sequence numbers or uids.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP

2005-02-22 Thread Max M
Fuzzyman wrote:
Mike Dee wrote:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

This will mean string literals in your source code will be encoded as
UTF8 - if you handle them with normal string operations you might get
funny results.
It means that you don't have to explicitely set the encoding on strings.
If your coding isn't set you must write:
ust = 'æøå'.decode('utf-8')
If it is set, you can just write:
ust = u'æøå'
And this string will automatically be utf-8 encoded:
st = 'æøå'
So you should be able to convert it to unicode without giving an encoding:
ust = unicode(st)
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Explicit or general importing of namespaces?

2005-02-28 Thread Max M
Michael Hoffman wrote:
But don't do "from Tkinter import *" for the reasons Diez has
identified in the FAQ.
It is so annoying to read some code and having to guess from where the 
do_complicated_stuff() function is imported from.

Explicit importing is by far the moste preferable.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] Re: python-dev Summary for 2005-01-16 through 2005-01-31

2005-03-02 Thread Max M
Martin v. Löwis wrote:
Steve Holden wrote:
The more I participate, the more I can relate to Eric Raymond's notion
of a "gift society". Volunteers give their contributions to the
community just because they want to, and they may get recognition in
return. But because these are gifts, you can just stop giving them away
at any time, and nobody should feel bad about doing so. The community
only is only entitled to the contributor saying so - finding somebody
else to step in is indeed optional.
I write a few open source projects myself, and I get virtually no 
feedback or patches on anything. Only complaints if there are bugs :-)

But on the other hand I use a lot of other peoples code without commenting.
I guess that is the way it must work. You take leadership in a small 
area, and you keep it as long as you care to.

So while it might not feel as a "brotherhood of shared effort" in the 
single sub-project, it might very well be on a higher level.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to make a list unique?

2005-03-08 Thread Max M
Eric Pederson wrote:
I have 


listA=[1,2,3,4,5,4,3,4,3,2,1]

and I want a list of only the unique members.
This seems inefficient, but works fine over my small sample lists:

listA=[a for a in set(listA)]
Is there a more efficient approach for cases where listA is large?

no. Even though the code can be a little simpler:
listA = list(Set(listA))
You don't even need to convert it to a list. You can just iterate over 
the set.

>>> la = [1,2,3,4,3,2,3,4,5]
>>> from sets import Set
>>> sa = Set(la)
>>> for itm in sa:
...     print itm
1
2
3
4
5
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: split a string with quoted parts into list

2005-03-10 Thread Max M
oliver wrote:
hi there
i'm experimanting with imaplib and came across stringts like
(\HasNoChildren) "." "INBOX.Sent Items"
in which the quotes are part of the string.
now i try to convert this into a list. assume the string is in the variable 
f, then i tried
f.split()
but i end up with
['(\\HasNoChildren)', '"."', '"INBOX.Sent', 'Items"']
so due to the sapce in "Sent Items" its is sepearted in two entries, what i 
don't want.

is there another way to convert a string with quoted sub entries into a list 
of strings?

In Twisteds protocols/imap4.py  module there is a function called 
parseNestedParens() that can be ripped out of the module.

I have used it for another project and put it into this attachment.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
"""
This code was stolen from Twisteds protocols/imap4.py  module
"""

import types, string

class IMAP4Exception(Exception):
def __init__(self, *args):
Exception.__init__(self, *args)

class MismatchedNesting(IMAP4Exception):
pass

class MismatchedQuoting(IMAP4Exception):
pass

def wildcardToRegexp(wildcard, delim=None):
wildcard = wildcard.replace('*', '(?:.*?)')
if delim is None:
wildcard = wildcard.replace('%', '(?:.*?)')
else:
wildcard = wildcard.replace('%', '(?:(?:[^%s])*?)' % re.escape(delim))
return re.compile(wildcard, re.I)

def splitQuoted(s):
"""Split a string into whitespace delimited tokens

Tokens that would otherwise be separated but are surrounded by \"
remain as a single token.  Any token that is not quoted and is
equal to \"NIL\" is tokenized as C{None}.

@type s: C{str}
@param s: The string to be split

@rtype: C{list} of C{str}
@return: A list of the resulting tokens

@raise MismatchedQuoting: Raised if an odd number of quotes are present
"""
s = s.strip()
result = []
inQuote = inWord = start = 0
for (i, c) in zip(range(len(s)), s):
if c == '"' and not inQuote:
inQuote = 1
start = i + 1
elif c == '"' and inQuote:
inQuote = 0
result.append(s[start:i])
start = i + 1
elif not inWord and not inQuote and c not in ('"' + string.whitespace):
inWord = 1
start = i
elif inWord and not inQuote and c in string.whitespace:
if s[start:i] == 'NIL':
result.append(None)
else:
result.append(s[start:i])
start = i
inWord = 0
if inQuote:
raise MismatchedQuoting(s)
if inWord:
if s[start:] == 'NIL':
result.append(None)
else:
result.append(s[start:])
return result


def splitOn(sequence, predicate, transformers):
result = []
mode = predicate(sequence[0])
tmp = [sequence[0]]
for e in sequence[1:]:
p = predicate(e)
if p != mode:
result.extend(transformers[mode](tmp))
tmp = [e]
mode = p
else:
tmp.append(e)
result.extend(transformers[mode](tmp))
return result


def collapseStrings(results):
"""
Turns a list of length-one strings and lists into a list of longer
strings and lists.  For example,

['a', 'b', ['c', 'd']] is returned as ['ab', ['cd']]

@type results: C{list} of C{str} and C{list}
@param results: The list to be collapsed

@rtype: C{list} of C{str} and C{list}
@return: A new list which is the collapsed form of C{results}
"""
copy = []
begun = None
listsList = [isinstance(s, types.ListType) for s in results]

pred = lambda e: isinstance(e, types.TupleType)
tran = {
0: lambda e: splitQuoted(''.join(e)),
1: lambda e: [''.join([i[0] for i in e])]
}
for (i, c, isList) in zip(range(len(results)), results, listsList):
if isList:
if begun is not None:
copy.extend(splitOn(results[begun:i], pred, tran))
begun = None
copy.append(collapseStrings(c))
elif begun is None:
begun = i
if begun is not None:
copy.extend(splitOn(results[begun:], pred, tran))
return copy




def parseNestedParens(s, handleLiteral = 1):
"""Parse an s-exp-like string into a more useful data structure.

@type s: C{str}
@param s: The s-exp-like string to parse

@rtype: C{list} of C{str} and C{list}
@return: A list containing the tokens present in the input.

@raise Mismatc

Re: csv module and unicode, when or workaround?

2005-03-12 Thread Max M
Chris wrote:
the current csv module cannot handle unicode the docs say, is there any 
workaround or is unicode support planned for the near future? in most 
cases support for characters in iso-8859-1(5) would be ok for my 
purposes but of course full unicode support would be great...
It doesn't support unicode, but you should not have problem 
importing/exporting encoded strings.

I have imported utf-8 encoded string with no trouble. But I might just 
have been lucky that they are inside the latin-1 range?

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-15 Thread Max M
Gregor Horvath wrote:
thanks are given to all
"problem" solved...

Personally I add a , after every list/tuple item. Also the last.
It also makes copy/pasting code easier.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


IMAP UTF-7, any codec for that anywhere?

2004-12-01 Thread Max M
Is there any codec available for handling The special UTF-7 codec for IMAP?
I have searched the web for info, but there only seem to be discussions 
about it. Not actual implementations.

This is what I am talking about:
http://www.faqs.org/rfcs/rfc2060.html
5.1.3.  Mailbox International Naming Convention
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: IMAP UTF-7, any codec for that anywhere?

2004-12-01 Thread Max M
Brian Quinlan wrote:
> Max M wrote:
>
>> Is there any codec available for handling The special UTF-7 codec for
>> IMAP?
> Is there something special do you need or is recipe OK?
>
>  >>> u"\u00ff".encode('utf-7')
> '+AP8-'
A recipe would be excellent. Unfortunately yours is no right. It should 
have looke like:

>>> imapUTF7Encode(u"\u00ff")
'&AP8-'
I believe you missed the 'special' in "The special UTF-7 codec for IMAP?"
Imap folders use a non-standard version of utf-7, where some characters 
are different.

I found som messages from 2001 on the net between a few Python unicode 
developers, where they discuss implementing it. But I cannot find an 
implementation anywhere.

I found a perl module that converts to/from the codec, but as usual that 
is regex hell. Well ok its not that difficult, but I still need to think 
to hard to parse Perl regex'

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help on program!!!

2004-12-03 Thread Max M
Dan Perl wrote:
That was also my impression.  Even the description of the problem looks like 
it's just copied from the assignment, so probably didn't even take the time 
to restate the problem in his own words.

But we're speculating.  Either way, this is not a normal request: "I need a 
program to do this, plz help!"  To the OP: you can't seriously expect us to 
actually write the program for you, what kind of help are you looking for?
This?
# -*- coding: latin-1 -*-
"""
  a.. Play a dice game of Craps using a random number generator to simulate
the roll of the dice, the code for the rolling of the dice should take place
in a user written module named rolldice.
  b.. The rules of the game are as follows:
a.. 1st roll, a score of 7 or 11 wins.
b.. 1st roll, a score of 2, 3, or 12 loses.
c.. 1st roll, any number other than those listed above becomes the goal
number, you must keep rolling until you roll the goal number again.  If a 7
is rolled before you goal number, you lose.
"""
import random
def rolldice():
dice1, dice2 = random.randint(1,6), random.randint(1,6)
print dice1, dice2
return dice1, dice2
first1, first2 = rolldice()
first = first1, first2
roll = 1
if first in (7, 11):
print 'Congratulations, you win in roll %s' % roll
elif first in (2,3,7):
print 'Too bad, you loose in roll %s' % roll
result = 'draw'
while result == 'draw':
dice1, dice2 = rolldice()
roll += 1
if dice1 + dice2 == 7:
print 'Too bad, you loose in roll %s' % roll
result = None
elif (dice1, dice2) == (first1, first2):
print 'Congratulations, you win in roll %s' % roll
result = None
Hopefully his teacher doesn't know about Google, or he can be expelled 
from school for using it.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help on program!!!

2004-12-03 Thread Max M
Dan Perl wrote:
"Max M" <[EMAIL PROTECTED]> wrote in message 

Most of us here have been students (or still 
are) and may sympathize with the OP, but personally I have been also a TA so 
I have seen the other side and that's where my sympathy lies now.
My reply was a joke... My normal response has allways been "why should 
we do your homework for you,"

So I just turned it upside down. "Naturally I will do homework for 
random users on usenet. here it is."

I simply found the idea of asking for homework cheats on usenet, where 
it can be traced very easily... well not very clever.

> "Hopefully" for whom?  For us, who may have to work with him someday 
or use
> a product that he developed?

I have a feeling that this guy has a future in IT. He definitely has 
management potential.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Psycopg 1.1.17 compiled binaries for windows, postgre 8.0.0-beta4 and python 2.3

2004-12-09 Thread Max M
Eino Mäkitalo wrote:
I had Visual C++ 6.0, so I compiled those
libpq.dll and psycopg.pyd.
if there are anyone to play with
Windows, Python 2.3 and Postgre-8.0.0-beta4 for windows like me.
You cat get those from: http://eino.net/html/python.html
Original psycopg source code is available in: 
http://initd.org/projects/psycopg1
Postgres runs fine on Windows now in a native version. And pgAdmin is a 
pretty nice tool.

A precompiled psycopg is the missing link. Thanks. I will try it out.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Persistent objects

2004-12-12 Thread Max M
Paul Rubin wrote:
Basically I wish there was a way to have persistent in-memory objects
in a Python app, maybe a multi-process one.  So you could have a
persistent dictionary d, and if you say 
   d[x] = Frob(foo=9, bar=23)
that creates a Frob instance and stores it in d[x].  Then if you
exit the app and restart it later, there'd be a way to bring d back
into the process and have that Frob instance be there.
Have you considdered using the standalone ZODB from Zope?
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: do you master list comprehensions?

2004-12-13 Thread Max M
Will Stuyvesant wrote:
I tried funnies like [[w for w in L] for L in data],
that is correct syntax, but you'd never guess.
That is absolutely correct. It's not a funnie at all. If you find it odd 
it's only because you are not used to list comprehensiones.

In that case you might be more comfortable with:
data = [['foo','bar','baz'],['my','your'],['holy','grail']]
result = []
for l in data:
result += l
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: do you master list comprehensions?

2004-12-13 Thread Max M
Fredrik Lundh wrote:
Max M wrote:

I tried funnies like [[w for w in L] for L in data],
That is absolutely correct. It's not a funnie at all.
well, syntactically correct or not, it doesn't do what he want...
Doh! *I* might not be used to list comprehensions then... You are right.
That example could have been expressed more clearly as:
result = data
;-)
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help need with converting Hex string to IEEE format float

2004-12-14 Thread Max M
[EMAIL PROTECTED] wrote:
Each of these numbers is a Hex byte making up a four byte (32 bit
Big-Endian) IEEE float. I have read this data into Python using
readlines and then line.split(). This gives me:
['80', '00', '00', '00']

Oh, programmers loves this kind stuff. You should get tons of answers.
##
st = '80 00 00 00'
import binascii
import struct
s = ''.join([binascii.a2b_hex(s) for s in st.split()])
v = struct.unpack("f", s)[0]
print v
##
regards Max M
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: python re - a not needed

2004-12-16 Thread Max M
kepes.krisztian wrote:
I want to get infos from a html, but I need all chars except <.
All chars is: over chr(31), and over (128) - hungarian accents.
The .* is very hungry, it is eat < chars too.
Instead of writing ad-hoc html parsers, use BeautifulSoup instead.
http://www.crummy.com/software/BeautifulSoup/
I will most likely do what you want in 2 or 3 lines of code.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why are tuples immutable?

2004-12-16 Thread Max M
Antoon Pardon wrote:
Well IMO there are two sides in this argument. The first is whether
or not python allows mutable keys. The second is whether or not
limiting keys to immutables in dictionaries provides a performance
gain.

The problem is that you don't understand what dicts are typically used 
for. Because of the nonliniarity in dict lookups, dicts are used for 
optimisation.

I actually think it's the most important tool for optimising Python code.
If dicts allowed mutable keys, a dict would need to run code that 
corresponds to::

def has_key(key):
for key in self.keys():
if a_key == key:
return True
return False
Using immutable keys, a code can be generated for the key, that can be 
efficiently stored in something like a binary tree.

This makes lookup *very much* faster, and is the speed concern that 
Python programmers care about.

Not the time taken to convert a list into a tuple.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: character encoding conversion

2004-12-13 Thread Max M
Christian Ergh wrote:
A smiple way to try out different encodings in a given order:
# -*- coding: latin-1 -*-
def get_encoded(st, encodings):
"Returns an encoding that doesn't fail"
for encoding in encodings:
try:
st_encoded = st.decode(encoding)
return st_encoded, encoding
except UnicodeError:
pass
st = 'Test characters æøå ÆØÅ'
encodings = ['utf-8', 'latin-1', 'ascii', ]
print get_encoded(st, encodings)
(u'Test characters \xe6\xf8\xe5 \xc6\xd8\xc5', 'latin-1')
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python To Send Emails Via Outlook Express

2004-12-19 Thread Max M
[EMAIL PROTECTED] wrote:
Thanks Fredrik,
That was my first impression too.
But all I want to do is use Python to instruct Outlook Express to send
an email.

Which you did! From the look of the traceback.
But your mailserver is configured in such a way that you cannot send 
mail from your machine using those email adresse, or you don't log on 
with the correct credentials.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a good use for lambda

2004-12-20 Thread Max M
The entity Fredrik Lundh wrote:

Isn't it about time you became xml avare, and changed that to:

?

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a good use for lambda

2004-12-20 Thread Max M
Steve Holden wrote:
Max M wrote:
Isn't it about time you became xml avare, and changed that to:

Yeah, but give the guy a break, we've all made feeble attempts at humor 
from time to time.
Hey, what's wrong with a little nørd humor...
I just found it amusing that somenone like Frederik Lundh, who has 
written xml stuff like ElementTree, uses something that reminds of an 
old HTML tag as a sig.


You realize, I suppose, that it's a reference to the 
fact that XHTML uses lower-case tags and allows self-closure with a 
trailing slash after the tag name?

let's-keep-that-christmas-spirit-coming-ly y'rs  - steve
:-) yes please.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python To Send Emails Via Outlook Express

2004-12-20 Thread Max M
[EMAIL PROTECTED] wrote:
Hi Steve,

When it comes to sending emails the user has the option of sending them
via smtp, or via there email client (eg outlook express).
I prefer the send method as this makes setting up the email parameters
a lot easier for the user.

If Outlook Express cannot be automated through COM, you are in abind. 
Maybe you should shange your tactics.

What about just fetching the settings from the client?
That way the send function will be the same, and you can control it. But 
the server settings could be fetched from the different clients.

It is probably much simpler to find those than it is to use them as the 
sender.

Most email clients can fetch the settings from other mail clients, so 
it's been done before.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: MIDI library recommendations, please?

2004-12-20 Thread Max M
Andrew Koenig wrote:
Are there widely used and recommended Python libraries that will let me
1) Interpret and generate MIDI messages easily?
Yes.
http://www.mxm.dk/products/public/pythonmidi

2) Allow me to select and communicate with MIDI devices attached to my 
computer?
There are some project which does that on different platforms. But I am 
not aware how well they work.

The best place to ask is probably on the Python Midi list at:
http://sourceforge.net/mail/?group_id=113783
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python To Send Emails Via Outlook Express

2004-12-24 Thread Max M
Lenard Lindstrom wrote:
[EMAIL PROTECTED] writes:

Hi Lenard,
You just beat me to it.
Suprise, suprise, I discovered the answer myself this time.
I have modified the script to allow the attachment(s) to still be
passed as a string.
Some error checking is also done to verify the attachment file exists.
I have also modified it so it can be used for multiple email addresses.
Here is the updated working script ...
-
import os
from ctypes import *
FLAGS = c_ulong
LHANDLE = c_ulong
LPLHANDLE = POINTER(LHANDLE)
# Return codes
SUCCESS_SUCCESS = 0
# Recipient class
MAPI_ORIG = 0
MAPI_TO = 1
NULL = c_void_p(None)
class MapiRecipDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('ulRecipClass', c_ulong),
('lpszName', c_char_p),
('lpszAddress', c_char_p),
('ulEIDSize', c_ulong),
('lpEntryID', c_void_p),
]
lpMapiRecipDesc = POINTER(MapiRecipDesc)
class MapiFileDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('flFlags', c_ulong),
('nPosition', c_ulong),
('lpszPathName', c_char_p),
('lpszFileName', c_char_p),
('lpFileType', c_void_p),
]
lpMapiFileDesc = POINTER(MapiFileDesc)
class MapiMessage(Structure):
_fields_ = [('ulReserved', c_ulong),
('lpszSubject', c_char_p),
('lpszNoteText', c_char_p),
('lpszMessageType', c_char_p),
('lpszDateReceived', c_char_p),
('lpszConversationID', c_char_p),
('flFlags', FLAGS),
('lpOriginator', lpMapiRecipDesc), # ignored?
('nRecipCount', c_ulong),
('lpRecips', lpMapiRecipDesc),
('nFileCount', c_ulong),
('lpFiles', lpMapiFileDesc),
]
lpMapiMessage = POINTER(MapiMessage)
MAPI = windll.mapi32
MAPISendMail=MAPI.MAPISendMail
MAPISendMail.restype = c_ulong  # Error code
MAPISendMail.argtypes = (LHANDLE,   # lhSession
c_ulong,   # ulUIParam
lpMapiMessage, # lpMessage
FLAGS, # lpFlags
c_ulong,   # ulReserved
)
def SendMail(recipient, subject, body, attachfiles):
"""Post an e-mail message using Simple MAPI
recipient - string: address to send to (multiple address sperated
with a semicolin)
subject - string: subject header
body - string: message text
attach - string: files to attach (multiple attachments sperated
with a semicolin)
Example usage
import simplemapi
simplemapi.SendMail("[EMAIL PROTECTED];[EMAIL PROTECTED]","My
Subject","My message body","c:\attachment1.txt;c:\attchment2")
"""
# get list of file attachments
attach = []
AttachWork = attachfiles.split(';')
#verify the attachment file exists
for file in AttachWork:
if os.path.exists(file):
attach.append(file)
attach = map( os.path.abspath, attach )
nFileCount = len(attach)
if attach:
MapiFileDesc_A = MapiFileDesc * len(attach)
fda = MapiFileDesc_A()
for fd, fa in zip(fda, attach):
fd.ulReserved = 0
fd.flFlags = 0
fd.nPosition = -1
fd.lpszPathName = fa
fd.lpszFileName = None
fd.lpFileType = None
lpFiles = fda
else:
# No attachments
lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL
# Get the number of recipients
RecipWork = recipient.split(';')
RecipCnt = len(RecipWork)
# Formulate the recipients
MapiRecipDesc_A = MapiRecipDesc * len(RecipWork)
rda = MapiRecipDesc_A()
for rd, ra in zip(rda, RecipWork):
rd.ulReserved = 0
rd.ulRecipClass = MAPI_TO
rd.lpszName = None
rd.lpszAddress = ra
rd.ulEIDSize = 0
rd.lpEntryID = None
recip = rda
# send the message
msg = MapiMessage(0, subject, body, None, None, None, 0,
cast(NULL, lpMapiRecipDesc), RecipCnt, recip,
nFileCount, lpFiles)
rc = MAPISendMail(0, 0, byref(msg), 0, 0)
if rc != SUCCESS_SUCCESS:
raise WindowsError, "MAPI error %i" % rc
---

Looks good.
Lenard Lindstrom
Nice quoting
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python To Send Emails Via Outlook Express

2004-12-25 Thread Max M
Steve Holden wrote:
Max M wrote:
Lenard Lindstrom wrote:

So what is this, some kind of competition? If you really though Lenard's 
quoting was a sin (since I took your remarks to be sardonic), how much 
more so was your gratuitous repetition thereof?
I thought that showing by example might have a better effect than just 
grumping.


Far more pleasant to either a) ignore a gaff by a possibly 
less-experienced usenet correspondent than yourself, or b) point out the 
error without repeating it, as I hope I have done here.
You are right.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create an object instance from a string??

2005-03-20 Thread Max M
Tian wrote:
How can I create an instance of an object from a string?
For example, I have a class Dog:

class Dog:
def bark(self):
print "Arf!!!"
def Factory(class_name):
classes = {
'Dog':Dog
}
return classes[class_name]
dog = Factory('Dog')()
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: IMAP4.search by message-id ?

2005-03-29 Thread Max M
Sean Dodsworth wrote:
Can anyone tell me how to get a message's number from the message-id 
using IMAP4.search?
I've tried this:
resp, items = server.search(None, 'HEADER', '"Message-id"', msgID)
but it gives me a 'bogus search criteria' error

Why do you need the 'HEADER'
Wouldn't this be enough?
resp, items = server.search(None, 'Message-id', msgID)
I am note shure if the msgId should be quoted. I assume not, as it will 
allways be an integer.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: oddness in string.find(sub,somestring)

2005-03-30 Thread Max M
MyHaz wrote:
import string
searched_string="abcdefg"
substring="123"
print string.find(substring,searched_string)
-1
searched_string=""
print string.find(substring,searched_string)
0
why would this be? And when is someone going to fix it :P
I don't know. When are you going to fix it?

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: oddness in string.find(sub,somestring)

2005-03-30 Thread Max M
MyHaz wrote:
why would this be? And when is someone going to fix it :P
Whoops ... This missed the previous message together with the wink ...
 ;-)
"When *are* you going to fix it ..."
substring="123"
import string
searched_string="abcdefg"
print string.find(searched_string, substring) # note the order
searched_string=""
print string.find(searched_string, substring)
You will not make that error if you use the string method instead.
searched_string.find(substring)
And you don't have to import anything either..
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generating RTF with Python

2005-03-31 Thread Max M
Axel Straschil wrote:
Hello!

does anyone know of a high-level solution to produce RTF from Python=20
(something similar to
Reportlab for producing PDF)?
Spend hours of googeling and searching, also in this NG, about two
months ago. My conclusion is: On windwos, maybe you can include some
hacks with dll's, under linux, linux support for generating rtf is none,
and so is python's.
My workaround was: 
http://www.research.att.com/sw/download/
This includes an html2rtf converter, which I access from python via
popen and temporary files. Not high-level, not very sexy ... ;-(

I looked at this a while ago, which might be a starter.
http://pyrtf.sourceforge.net/
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with national characters

2005-03-31 Thread Max M
Leif B. Kristensen wrote:
Is there a way around this problem? My character set in Linux is
ISO-8859-1. In Windows 2000 it should be the equivavent Latin-1, though
I'm not sure about which character set the command shell is using.
The unicode methods seems to do it correctly. So you can decode your 
strings as unicode, do the transfom, and encode it back as latin1.

print repr('før'.decode('latin-1').upper().encode('latin-1')) #
'F\xd8R'
print repr('FØR'.decode('latin-1').encode('latin-1'))
'F\xd8R'
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems extracting attachment from email

2005-04-08 Thread Max M
foten wrote:
The problem I'm having is when I'm trying to extract the
attachement using
f=open(Filename, "wb")
f.write(msg.get_payload(decode=1))
f.close()
Not the whole message is decoded and stored!
When only trying
f.write(msg.get_payload())
I see that the last 255 bytes are missing.
How is this possible, I receive every last byte from stdin?

I don't think its a Python problem. Those methods are used in a lot of 
places. Your file is most likely not what it is supposed to be.

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: doubt regarding Conversion of date into timestamp

2005-04-08 Thread Max M
praba kar wrote:
Dear All,
 I am new to Python I want to know how to 
change a time into timestamp

Is there any specific reason for not using datetime instead of time ?
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can dictionary values access their keys?

2005-04-08 Thread Max M
Matthew Thorley wrote:
I am creating an object database to store information about network
devices, e.g. switches and routers.

Possible usefull pages?
http://www.python.org/doc/essays/graphs.html
more at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: To decode the Subject =?iso-8859-2?Q?=... in email in python

2005-04-20 Thread Max M
Dan Polansky wrote:
When parsing messages using python's libraries email and mailbox, the
subject is often encoded using some kind of = notation. Apparently, the
encoding used in this notation is specified like =?iso-8859-2?Q?=... or
=?iso-8859-2?B?=. Is there a python library function to decode such a
subject, returning a unicode string? The use would be like
  human_readable = cool_library.decode_equals(message['Subject'])

parts = email.Header.decode_header(header)
new_header = email.Header.make_header(parts)
human_readable = unicode(new_header)

--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: MidiToText : EventDispatcher instance has no attribute 'sysex_events'

2006-01-01 Thread Max M
Carsten Haese wrote:
> On Fri, 2005-12-30 at 09:52, tim wrote:
> 
>>Trying to convert midi to text using MidiToText.py.
>>I get the following:
>>
>>midi_port: 0
>>Traceback (most recent call last):
>>  File "MidiToText.py", line 176, in ?
>>midiIn.read()
>>  File "C:\Python24\Lib\site-packages\midi\MidiInFile.py", line 24, in read
>>p.parseMTrkChunks()
>>  File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 167, 
>>in parseMTrkChunks
>>self.parseMTrkChunk() # this is where it's at!
>>  File "C:\Python24\Lib\site-packages\midi\MidiFileParser.py", line 129, 
>>in parseMTrkChunk
>>dispatch.sysex_events(sysex_data)
>>AttributeError: EventDispatcher instance has no attribute 'sysex_events'
> 
> 
> Try changing "def sysex_event(self, data):" in
> ...\midi\EventDispatcher.py to "def sysex_events(self, data):"

Or just do a search and replace on the whole package::

search: sysex_events(
replace: sysex_event(

Apparently I have been inconsistent in my naming.

New version at:

http://www.mxm.dk/products/public/pythonmidi/download


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are there anybody using python as the script engine for ASP?

2006-01-05 Thread Max M
[EMAIL PROTECTED] wrote:
> Hi everyone, I'm planning using python with asp, and wonder if some
> people do use python/asp in real life projects. (I'm going to)

I used to back in the days, and it was fine.

A lot better than VBScript / JScript that was available then.

Perhaps IronPython would be worth trying out, though a bit premature.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft IronPython?

2006-01-06 Thread Max M
EP wrote:
> Luis M. González wrote:
> 
>> Will Microsoft hurt Python?
>>  
> I think it is naive to ignore the fact that Microsoft could hurt Python, 
> though there may be nothing anyone can do.
> 
>> How?
> 
> - create a more prevalent version of "Python" that is less Pythonic or 
> undermines some of the principles of the language, basically usurping 


First of they would need to make Python a strategic platform for 
corporations, so that it was used practically everywhere on Windows.

Then it would have the powerbase to change the lanuage and make an 
incompatible version that they could control.

As far as I can see C## has that role for them. So I don't see how 
Python should be in any danger.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Two Classes In Two Files

2006-08-09 Thread Max M
[EMAIL PROTECTED] wrote:
> I just started working with Python and ran into an annoyance. Is there
> a way to avoid having to use the "from xxx import yyy" syntax from
> files in the same directory? I'm sure it's been asked a million times,
> but I can't seem to find the answer.

Probably none that are better.

1:
import one
class Two(one.One)

2:
put both classes in the same file.


It's just the way it is. Why worry about it?


> For example, I have two classes stored in separate files as such.
> 
> File: one.py
> 
> class One:
>   def methodA(self):
> print "class One"
>   def methodB(self):
> print "class One"
> 
> 
> File two.py
> 
> from one import One
> 
> class Two(One):
>   def methodA(self):
> print "class Two"
> 
> if __name__ == "__main__":
>   x = Two()
>   x.methodA()
>   x.methodB()
> 
> When I run the Two.py file, I get the expected output but I'd like to
> eliminate the from line in two.py.
> 


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Memory Management in python 2.5

2006-10-09 Thread Max M
[EMAIL PROTECTED] skrev:
> Hi, I am starting to have a look to a python program that does not free
> memory (I am using python 2.4.3). As I have read about a new memory
> management in python 2.5 (http://evanjones.ca/python-memory.html) I
> decided to try the program with the new version.
> With the new version of python the memory consumption is the same. Now
> I am asking myself if  python 2.5 has any improving  in memory
> management or maybe not yet. Thank you.

In previous versions Python collected memory, but never released it 
again. It simply kept on to it, so it could reuse it again later.

 From 2.5 onwards it should release most of the unused memory. However 
it doesn't use less memory. The peak memory usage should be the same as 
before. So for one-off programs that starts up and runs once, there 
should not be much gain.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Sarcasm and irony

2006-10-10 Thread Max M
bryan rasmussen skrev:
> On 10/10/06, Steve Holden <[EMAIL PROTECTED]> wrote:

>> ... in America. It's well-known among Brits that Americans don't
>> understand irony. They can be pretty oblique when it come to sarcasms
>> too, for that matter.
> 
> is that 'in America' meant to be an addendum to what I said, as in
> this is the situation in America and not elsewhere? If so I should
> probably point out that I am writing from Denmark and was thinking
> specifically of a situation where a dane told me they were being
> 'ironic' (when what they meant, obviously, was that they were being
> ironical), when I asked what they meant by that they said "saying the
> opposite of what I mean" I responded: "so, in other words, what you
> mean by irony is 'sarcasm'" She responded "yes, that's what it means"


Are you an american?

Irony does mean that one says the opposite of what one really means.

If you do it for humor its irony, if you do it for mocking it is sarcasm.

So now I see... americans really *do* understand irony.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Sarcasm and irony

2006-10-10 Thread Max M
bryan rasmussen skrev:

> Well irony originally started out as a very specific concept of the
> Ancient Greek drama, this is what we nowadays refer to as Dramatic
> Irony but it is the original irony. Irony then became a literary
> concept for plot elements similar to Dramatic irony in books, or a
> weaker type of the Dramatic irony found in the plays of Shakespeare.
> People then noticed that life was at times ironic in the literary
> manner.

Yes and in Rome "salary" meant getting a bag of salt. Concepts changes.


> Nowadays the use of the word irony has degenerated to by
> pretty much synonymous with sarcasm.

As a Dane that is a Chronic Ironic, I beg to differ.

In Denmark at least there is a lot of difference between irony and 
sarcasm. Irony is the main form of humor here, and danes takes to it 
easily. People being sarcastic we don't much like.

But I guess that it can be hard to se the difference for someone not 
used to irony.

I believe the reason that irony works here is that we have such a 
homogenous society. Somewhere like the US where the cultural differences 
are larger, it is probably a lot harder for irony to be taken as such 
and not as sarcasm.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: send an email with picture/rich text format in the body

2006-05-29 Thread Max M
Ben Finney wrote:
> "anya" <[EMAIL PROTECTED]> writes:
> 
> 
>>Acctualy there is a solution:
>>see  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810
> 
> 
> Again, sending anything but plain text as the message body ensures
> that your message is unreadable to a large number of people using a
> variety of software. It's your choice whether to restrict your
> audience in this way, but know that that's what you're doing.


90% of users are non-technical users who use standard email readers, 
that can easily read html messages.

In my experience the kind of user that receives emails with html and 
pictures often prefer it that way.

So why bother with the lecture? I cannot remember when I have last 
received a relevant email that I could not read in text mode.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: send an email with picture/rich text format in the body

2006-05-29 Thread Max M
Scott David Daniels wrote:
> Max M wrote:
> 
>> 90% of users are non-technical users who use standard email readers, 
>> that can easily read html messages.
>>
>> In my experience the kind of user that receives emails with html and 
>> pictures often prefer it that way.
>>
>> So why bother with the lecture? I cannot remember when I have last 
>> received a relevant email that I could not read in text mode.
> 
> 
> Because
>   (A) This _is_ a technical newsgroup with mores you are violating.

*I* am? How? By disagreeing on how technology should be used?


>   (B) Some of us "technical users" avoid such email/news readers
>   precisely because they can cause tracking across the web.

Yes but some times it's just simpler to send formatted text and images.
I also use text only email. But I don't believe everybody else has to.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-30 Thread Max M
John Bokma wrote:
> [EMAIL PROTECTED] wrote:

> Your first question should be: Is it alright that Xah harasses 5 
> newsgroups? Or maybe work on your spelling, harass is with one r, but 
> maybe you didn't read the subject, which wouldn't amaze me, since you 
> sound like you should be spending time on MySpace OMG!.


I assume that the single l in alright is the courteous misspelling that 
should allways be in a posting, when correcting other peoples speling?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best Python Editor

2006-05-31 Thread Max M
Manoj Kumar P wrote:
> Hi,
> 
> Can anyone tell me a good python editor/IDE?
> It would be great if you can provide the download link also.


pydev on top of eclipse is a nice tool.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variable name has a typo, but code still works. Why?

2006-05-31 Thread Max M
mateus wrote:
> print "hello world"
> 
> I have a nested loop where the outer loop iterates over key value pairs
> of a dictionary and the inner loop iterates over a list each list of
> which is a mapped value from the dictionary
> 
> def showReport(self):
> for dev, sessions in self.logger.items():
> for tree in session:
> self.addTestItem(self, tree)
> 
> What I don't understand is why this executes w/o any problems when
> "sessions" was spelled as plural (sessionS) while later being spelled
> in the singular (session).
> 
> Is there some type of name resolution of local variables where Python
> makes assumptions?


No. You are probably running your script in an ide that keeps an old 
variable hanging around.

Try it from a command promt.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-19 Thread Max M
bruno at modulix wrote:

>> Or did you just like what you saw and decided to learn it for fun?
> 
> Well, I haven't be really impressed the first time - note that it was at
> the very end of the last century, with v1.5.2. 


1.5.2 was an excellent version. Not really that different in use than 
current version.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-20 Thread Max M
bruno at modulix wrote:
> Max M wrote:
>> bruno at modulix wrote:
>>
>>>> Or did you just like what you saw and decided to learn it for fun?
>>>
>>> Well, I haven't be really impressed the first time - note that it was at
>>> the very end of the last century, with v1.5.2. 
>>
>>
>> 1.5.2 was an excellent version. Not really that different in use than
>> current version.
> 
> Nope, "not really that different" - we were just missing list-comps,
> generators, new-style classes, classmethods, staticmethods, usable
> metaclasses, descriptors, @decorators sugar, extended slices, and a few
> other goodies coming in 2.5 like coroutines and with: statement...


I wrote "different in use". Which is not the same as saying it has not 
changed. The general feel of coding in Python is exactly the same to me.

I believe that most of those changes you mention are rarely used by most 
programmers.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A game idea.

2006-06-27 Thread Max M
defcon8 wrote:
> I have had what I think is quite a nice game idea, but I don't really
> have the experience or knowledge to go about it. Would anyone be
> willing to start a game project?


Ideas are a dime a dozen. Implementation is the hard part.

If you want something done, you will have to do it yourself.

I am not trying to be negative, but I will bet you that every competent 
programmer on the list has 1+ project that she would love to do, if she 
just had the time.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The lib email parse problem...

2006-08-29 Thread Max M
叮叮当当 wrote:
> this is not enough.
> 
> when a part is mulitpart/alternative, i must find out which sub part i
> need, not all the subparts. so i must know when the alternative is
> ended.


Have you tried the email module at all?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: sending emails using python

2006-09-07 Thread Max M
sridhar wrote:
> iam having user account on an exchangeserver.
> with that can i send an email using python?
> 
> if iam using the following code iam getting error
> 
> 
> fromAddress = '[EMAIL PROTECTED]'
> toAddress = '[EMAIL PROTECTED]'
> msg = "Subject: Hello\n\nThis is the body of the message."
> import smtplib
> server = smtplib.SMTP("hstmsg002",25)
> server.sendmail(fromAddress, toAddress, msg)


Do yourself a favor and use the email module to construct your messages 
with. Constructing messages by hand can lead you into so many traps. 
Especially if you are using international characters in you messages.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with email.Generator.Generator

2006-09-12 Thread Max M
Chris Withers wrote:
> Chris Withers wrote:
>> print msg.as_string()
>>
>> MIME-Version: 1.0
>> Content-Type: text/plain; charset; charset="utf-8"
> ^^^
> Actually, even this isn't correct as you can see above...
> 
>> charset = Charset('utf-8')
>> msg = MIMEText('','plain',None)
>> msg.set_payload(u'Some text with chars that need encoding:\xa3',charset)

> Has no-one ever successfully generated a correctly formatted email with 
> email.MIMEText where the message includes non-ascii characters?!

What is the problem with encoding the message as utf-8 before setting 
the payload? That has always worked for me.


pl = u'Some text with chars that need encoding:\xa3'.encode('utf-8')
msg.set_payload(pl ,charset)

 From the docs:

"""
The payload is either a string in the case of simple message objects or 
a list of Message objects for MIME container documents (e.g. multipart/* 
and message/rfc822)
"""

Message objects are always encoded strings. I don't remember seeing that 
it should be possible to use a unicode string as a message.

The charset passed in set_payload(pl ,charset) is the charset the the 
string *is* encoded in. Not the charset it *should* be encoded in.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with email.Generator.Generator

2006-09-12 Thread Max M
Chris Withers wrote:
> Max M wrote:
>>  From the docs:
>>
>> """
>> The payload is either a string in the case of simple message objects 
>> or a list of Message objects for MIME container documents (e.g. 
>> multipart/* and message/rfc822)
>> """
> 
> Where'd you find that? I must have missed it in my digging :-S


End of third paragraph:

http://docs.python.org/lib/module-email.Message.html


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone:  +45 66 11 84 94
Mobile: +45 29 93 42 96
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >