Re: ftp recursively

2008-03-19 Thread Jeff Schwab
Paul Rubin wrote:
> Jeff Schwab <[EMAIL PROTECTED]> writes:
>> ftping it as a flat file, and untarring it on the other side.  Of
>> course, the motivation wasn't just to get the files from point A to
>> point B using Unix (which I already know how to do), but to take
>> advantage of an opportunity to learn some Python; next time, I'll try
>> the ftpmirror.py script if it's generic enough, or ftplib if there are
>> more specific requirements.
> 
> I see, that wasn't clear in your original post.  You should look at
> the os.walk function if you want to know how to traverse a directory
> tree (maybe you are already doing this).

I thought os.walk was for locally mounted directories...  How is it 
relevant on remote filesystems?

> Also, for security reasons,
> it's getting somewhat uncommon, and is generally not a good idea to
> run an ftpd these days, even on a LAN.  It's more usual these days
> to transfer all files by rcp or rsync tunnelled through ssh.

Don't shoot the messenger, but you're severely confused here.  Whether 
you're using ftp, rcp, or rsync is a completely separate issue to 
whether you're running over ssl (which I assume you meant by ssh).

FTP is a work-horse protocol for transferring files.  It's going to be 
with us for a long, long time.  There are various clients and servers 
built on it, including the traditional ftp command-line tools on Unix 
and Windows.

rcp is a very simple tool for copying files from one (potentially 
remote) place to another.  The point of rcp is that its interface is 
similar to cp, so the flags are easy to remember.  Modern Unix and Linux 
systems usually include secure versions of both ftp and rcp, called sftp 
and scp, respectively.

The point of rsync is to keep a local directory tree in sync with a 
remote one, by transferring only change-sets that are conceptually 
similar to patches.  If you're only transferring files once, there's no 
particular benefit (AFAIK) to using rsync rather than some kind of 
recursive ftp.
-- 
http://mail.python.org/mailman/listinfo/python-list


dividing tuple elements with an int or float

2008-03-19 Thread royG
hi
i am trying to resize some images.First i'd read the size as a 2
tuple  and then i want to divide it by 2 or 4 or 2.5 etc..

suppose
origsz=(400,300)
i want to divide the origsize by 2.5 so i can resize to (160,120)

scale=2.5
how can i get the newsz?
obviously origsz/2.5 won't work  ..
thanks
RG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml sax

2008-03-19 Thread Timothy Wu
Oh right, why didn't I think of that. =)

Many thanks.

Timothy


On Thu, Mar 20, 2008 at 1:45 AM, Robert Bossy <[EMAIL PROTECTED]>
wrote:

> Timothy Wu wrote:
> > Hi,
> >
> > I am using  xml.sax.handler.ContentHandler to parse some simple xml.
> >
> > I want to detect be able to parse the content of this tag embedded in
> > the XML.
> > 174
> >
> >
> > Is the proper way of doing so involving finding the "Id" tag
> > from startElement(), setting flag when seeing one, and in characters(),
> > when seeing that flag set, save the content?
> >
> > What if multiple tags of the same name are nested at different levels
> >
> > and I want to differentiate them? I would be setting a flag for each
> level.
> > I can imagine things get pretty messy when flags are all around.
> >
> Hi,
>
> You could have a list of all opened elements from the root to the
> innermost. To keep such a list, you append the name of the element to
> this stack at the end of startElement() and pop it off at the end of
> endElement().
>
> In this way you have acces to the path of the current parser position.
> In order to differentiate between character data in Id and in Id/Id, you
> just have to iterate at the last elements of the list.
>
> Cheers,
> RB
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: keeping state in an iterator object by rebinding next()

2008-03-19 Thread iteration . nth
On Mar 19, 3:36 pm, Wilbert Berendsen <[EMAIL PROTECTED]> wrote:
> Hi,
>
> i am writing a simple parser, that generates tokens. The parser needs to
> maintain some state, because some parts of the file consist of different
> tokens. I thought the object could simply remember its state by assigning
> it's next() method to the method that is currently parsing. When the state
> changes, the called method rebinds next() and the next token will be returned
> by that function. Here's an example, proving that this indeed works.
>
> >>> class A:
>
> ...  def a(self):
> ...   self.next = self.b
> ...   return 1
> ...  def b(self):
> ...   self.next = self.a
> ...   return 2
> ...  def __iter__(self):
> ...   return self
> ...>>> a=A()
> >>> a.a()
> 1
> >>> a.next()
> 2
> >>> a.next()
> 1
> >>> j=0
> >>> for i in a:
>
> ...  j += 1
> ...  if j > 10: break# prevent from running endlessly
> ...  print i
> ...
> 2
> 1
> 2
> 1
> 2
> 1
> 2
> 1
> 2
> 1
>
>
>
> my question is: is this legal Python? An iterator could save the next() method
> object, and in that case it could stop working It works now, because
> apparently the for- construct resolves 'next' each time for the object before
> calling it.
>
> The other solution would be just jumping to the correct method from within the
> next() method. But that gives an extra call...
>
> Met vriendelijke groet,
> Wilbert Berendsen
>
> --http://www.wilbertberendsen.nl/
> "You must be the change you wish to see in the world."
> -- Mahatma Gandi



 "You must be the change you wish to see in the world."
-- Mahatma Gandi

JFYI: Mahatma Gandhi  (NOT Gandi).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ADO error - large data set

2008-03-19 Thread Gyula
Ok. After several tries, I think I found out why it breaks and it has
nothing to do with the number of records...

Here is the code/ see notes below:

# code starts here
# First import wincom32 client
from win32com.client import *

# Create the ADO Connection object via COM
oConn = Dispatch(r'ADODB.Connection')

# Now set the connection properties via the ConnectionString
oConn.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" + \
"DATA SOURCE=C:/Documents and Settings/user/Desktop/PythonWS/data/
anydata.mdb;"

# Now open the connection
oConn.Open()

# create a recordset
rs = Dispatch(r'ADODB.Recordset')
rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic,
constants.adLockOptimistic)

rs.MoveFirst()
counter = 1
while not rs.EOF:
print counter   # do nothing, just cycle through
counter += 1
rs.MoveNext()

# cleanup
rs.Close()
rs = None
oConn.Close()
oConn = None
print 'Done!'
# code ends here

the line where it breaks:
rs.Open('SELECT TOP 300 * FROM input;', oConn, constants.adOpenStatic,
constants.adLockOptimistic)

'input' is supposed to be the table name, but it breaks in Python when
you want to open the recordset.

I need to use:
rs.Open('SELECT TOP 300 * FROM [input];', oConn,
constants.adOpenStatic, constants.adLockOptimistic)

as input is an SQL keyword...argh.

Gyula


On Mar 19, 5:17 pm, Gyula <[EMAIL PROTECTED]> wrote:
> Thanks! I will give it a try. It seems though that I get stuck on
> rs.Open that makes no sense. I was wondering about pagesize or other
> registry settings that might cause this? Will try to track down any
> bad data first...
> gg
>
> On Mar 19, 3:27 pm, "dsavitsk" <[EMAIL PROTECTED]> wrote:
>
> > Is it possible there is some bad data in the larger db? This is asinine, but
> > maybe write a small script that adds some data, then opens and closes the
> > db, then repeats this. If this is a size issue, then you can at least narrow
> > it down to where the size limit is? And, if it isn't you should be able to
> > figure that out, too. Otherwise, play around with the locking and cursor
> > options.
>
> > -d
>
> > "Gyula" <[EMAIL PROTECTED]> wrote in message
>
> >news:[EMAIL PROTECTED]
>
> > > Hi there,
>
> > > I have been running Python to tap into an MS Access 2003 database
> > > using ADO (PythonWin+COM). Everything works great creating recordsets
> > > etc. when I open a table with a small number of records. However, when
> > > I try to run the same Python code with a large table (>100,000) I get:
>
> > > Traceback (most recent call last):
> > >  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
> > > \scriptutils.py", line 310, in RunScript
> > >exec codeObject in __main__.__dict__
> > >  File "C:\Documents and Settings\user\Desktop\PythonWS\scripts
> > > \readmsaccess.py", line 43, in 
> > >rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3)
> > >  File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C-
> > > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open
> > >, ActiveConnection, CursorType, LockType, Options)
> > > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
> > > 5003251, -2147467259), None)
>
> > > The small and large table structures are identical, all I do is change
> > > the tblname from input1000 (1000 records) to input (>10 records).
> > > I use optimistic locking and keyset cursor..nothing out of the
> > > ordinary?
>
> > > Any ideas? ADO 2.8 is what I am using.
>
> > > Thanks a lot!
> > > GG

'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie] using ElementTree, how to add doctype and xml pi

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 20:53:49 -0300, dave berk <[EMAIL PROTECTED]>  
escribió:

> I have an svg file i'm creating on the fly. How do I add the doctype and  
> xml
> pi? They're not an element per se, and there is no function to add them.

The easiest way (but perhaps not-so-pure) is to just write those lines by  
hand before the document itself; see a recent post about "Inserting DTD  
statement to XML"

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 20:16:36 -0300, John Machin <[EMAIL PROTECTED]>  
escribió:
> On Mar 20, 9:14 am, sturlamolden <[EMAIL PROTECTED]> wrote:

>> Is a Python set implemented using a hash table?
>
> What don't you understand about the comments in the first two
> screenfuls of Objects/setobject.c?

That comment was unnecesarily harsh, don't you think?

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.getsize() on Windows

2008-03-19 Thread Steven D'Aprano
On Wed, 19 Mar 2008 12:34:34 +, Duncan Booth wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>> This whole approach
>> assumes that Windows does the sensible thing of returning a unique
> error
>> code when you try to open a file for reading that is already open for
>> writing.
>> 
>> 
> So how would you use a file to share data then?


I see I was a little unclear.

What I meant to say was that I assumed that Windows returned a specific 
error code of "file is busy" as opposed to "you don't have permission to 
access this file right now" without specifying whether this is a 
permanent permissions error or a temporary file busy error.


 
> By default Python on Windows allows you to open a file for reading
> unless you specify a sharing mode which prevents it: 

But the OP is talking about another process having opened the file for 
WRITING, not reading. It's that other process that has exclusive access, 
and the OP was trying to determine when it was safe to attempt opening 
the file according to whether or not it was still growing.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inserting DTD statement to XML

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 15:33:19 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:

> I am new to Python and I am writing a script to build a XML document
> and post it to a website.  I have a working script but need to insert
> a DTD statement in my XML document and can't find out how to do this.
> I am using "from xml.dom.minidom import Document"
>
> Some code I am using is:
>
>   doc = Document()
>   rootNode = doc.createElement("employees")
>   doc.appendChild(rootNode )
>
> I get the following when I print it out
>
> 
> 
>...
> 
>What I would like is to have something like:
>
> 
> 
> 
>...
> 
>

Try this:

 from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
dt = impl.createDocumentType("employees", "-//ICES//DTD ICES  
EMPLOYEES//EN", "")
doc = impl.createDocument(None, "employees", dt)
root = doc.documentElement
node = doc.createElement("foo")
node.setAttribute("some","attribute")
node.setAttribute("attr","value")
root.appendChild(node)
print doc.toxml()

But unless you *have* to use DOM for some reason, better switch to  
another, more "pythonic" library. Like ElementTree or lxml (both implement  
the same interface); the former comes with Python 2.5, the later you can  
get from http://codespeak.net/lxml

import xml.etree.ElementTree as ET
root = ET.Element("employees")
ET.SubElement(root, "foo", some="attribute", attr="value")
ET.dump(root)
# 
# ElementTree cannot generate a doctype header, do it by hand
f = open("test.xml", "w")
f.write('\n')
f.write('\n')
f.write(ET.tostring(root))
f.close()

(note: the lxml version may have doctype support)

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Nicholas F. Fabry


On Mar 19, 2008, at 18:32, Steven D'Aprano wrote:


On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote:


To summarize my proposal VERY briefly:


- Make aware datetime objects display in local time, but calculate/
compare in UTC.


Your proposal is ambiguous. What does that mean? Can you give an  
example?





That's why I said it was the VERY brief version - here is a longer  
version.


I would like a datetime to display local times, since if I create it  
with a specific tzinfo timezone, that implies I'm interested in what  
clocks in that time zone say.


For example:

>>> from datetime import datetime
>>> from dateutil.tz import gettz
>>> NYC = gettz('America/New_York')
>>> UTC = gettz('UTC')
>>> wake_up_time = datetime(2008,3,8,15,30,0,tzinfo=NYC)
>>> print wake_up_time
2008-03-08 15:30:00-05:00
>>> print wake_up_time.hour
15

This is the behavior I want - if I create a datetime in a specific  
timezone, I wish to know the member information (date, hour, second,  
etc.) in that timezone.


However, when I calculate with it, I can get wrong answers.

>>> a_later_time = datetime(2008,3,9,15,30,0,tzinfo=NYC)
>>> print a_later_time - wake_up_time
1 day, 0:00:00

This is incorrect, because a_later_time is in daylight saving time,  
but the eariler time is in standard time - the gap is actually 23:00  
hours.


>>> print a_later_time.astimezone(UTC) - wake_up_time.astimezone(UTC)
23:00

The reason datetime performs this calculation incorrectly is  
documented - if the tzinfo members are the same object, it ignores  
them and makes the calculation as though the two datetimes were  
naive.  If the tzinfo objects are different, even if they correspond  
to the exact same ruleset, then datetime does the job correctly.


>>> import copy
>>> ALT_NYC = copy.deepcopy(NYC)
>>> the_same_later_time = datetime(2008,3,9,15,30,0,tzinfo=ALT_NYC)
>>> print the_same_later_time - wake_up_time
23:00

The results of the calculation should not be dependent on whether the  
tzinfo object is the same or not, but what it's .utcoffset() method  
returns.  Or, to summarize, ALL calculations with aware datetime  
objects should first change the datetime objects to UTC so the  
calculations are done correctly.


Changing all times to UTC creation, aside from making ugly code, now  
forces a conversion back to local time, with more code, any time you  
want to display date and time information in the local time zone.   
This is not a good, pythonic solution.






- Raise exceptions when an illegal or ambiguous datetime is  
instantated.


You mean like they already do?


datetime.datetime(2008, 03, 35)  # 35th of March

Traceback (most recent call last):
 File "", line 1, in 
ValueError: day is out of range for month




However, the following does NOT raise an exception, and it should.

>>> a_time = datetime(2008, 3, 9, 1, 30, 0, tzinfo=NYC)
>>> print a_time
2008-03-09 01:30:00-05:00

The problem is that there IS no local wallclock time of 0130 on March  
9, 2008 in New York.  At 0100, local clocks jump to 0200 and proceed  
from there.  A local wallclock time of 0130 on March 9, 2008 in New  
York is meaningless - it should not occur.  Therefore, if a programmer  
is (for example) parsing local times (say, out of a schedule book),  
and an illegal time like this appears, instead of an exception  
immediately being raised to alert him/her of the faulty source data,  
the program *assumes* the illegal local time was 'meant' to be in  
standard time, and sends it merrily on its way... making it much  
harder when errors crop up later to figure out their source.







As for ambiguous, how can datetime arguments be ambiguous?

   Help on class datetime in module datetime:

   class datetime(date)
|  datetime(year, month, day[, hour[, minute[, second[,
microsecond[,tzinfo])


What possible ambiguity is there?



Continuing on from before:

>>> b_time = datetime(2008, 11, 2, 1, 30, 0, tzinfo=NYC)
>>> print b_time
2008-11-02 01:30:00-05:00

There is a little problem with this, though.  At 2008 Nov 2 at 0200  
Eastern Daylight Time, the clocks swing back one hour, to 0100, and  
essentially repeat the hour between 0100 and 0200 again.  So - is  
b_time 0130 Eastern STANDARD Time, or is it 0130 Eastern DAYLIGHT  
Time?  Simply providing a tzinfo class does not resolve this  
ambiguity, so it is again *assumed* that you 'meant' standard time.   
That may or may not be true, depending on the source data and other  
external factors.
A good datetime library (or tzinfo library) should alert you to this  
fact.  Isn't Explict better than Implicit?


A further problem is that it is now impossible to specify using tzinfo  
= NYC, a time corresponding to 2008 Nov 2, 0530 UTC, or in other  
words, 2008 Nov 2 0130 EDT.  If you try it directly, as above, you get  
2008 Nov 2 0130 EST, which is 0630 UTC.  If you create the time 2008  
Nov 2 0530 UTC, and then use .astimezone(NYC), you will g

Re: finding items that occur more than once in a list

2008-03-19 Thread sturlamolden
On 20 Mar, 00:16, John Machin <[EMAIL PROTECTED]> wrote:

> What don't you understand about the comments in the first two
> screenfuls of Objects/setobject.c?

I had not looked at it, but now I have. Is seems Hettinger is the
author :) Ok, so sets are implemented as hash tables. Then I agree,
use Raymond Hettinger's solution.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ADO error - large data set

2008-03-19 Thread Gyula
Thanks! I will give it a try. It seems though that I get stuck on
rs.Open that makes no sense. I was wondering about pagesize or other
registry settings that might cause this? Will try to track down any
bad data first...
gg

On Mar 19, 3:27 pm, "dsavitsk" <[EMAIL PROTECTED]> wrote:
> Is it possible there is some bad data in the larger db? This is asinine, but
> maybe write a small script that adds some data, then opens and closes the
> db, then repeats this. If this is a size issue, then you can at least narrow
> it down to where the size limit is? And, if it isn't you should be able to
> figure that out, too. Otherwise, play around with the locking and cursor
> options.
>
> -d
>
> "Gyula" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > Hi there,
>
> > I have been running Python to tap into an MS Access 2003 database
> > using ADO (PythonWin+COM). Everything works great creating recordsets
> > etc. when I open a table with a small number of records. However, when
> > I try to run the same Python code with a large table (>100,000) I get:
>
> > Traceback (most recent call last):
> >  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
> > \scriptutils.py", line 310, in RunScript
> >exec codeObject in __main__.__dict__
> >  File "C:\Documents and Settings\user\Desktop\PythonWS\scripts
> > \readmsaccess.py", line 43, in 
> >rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3)
> >  File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C-
> > D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open
> >, ActiveConnection, CursorType, LockType, Options)
> > com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
> > 5003251, -2147467259), None)
>
> > The small and large table structures are identical, all I do is change
> > the tblname from input1000 (1000 records) to input (>10 records).
> > I use optimistic locking and keyset cursor..nothing out of the
> > ordinary?
>
> > Any ideas? ADO 2.8 is what I am using.
>
> > Thanks a lot!
> > GG



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slicing a list but in downward fashion

2008-03-19 Thread Mensanator
On Mar 19, 6:37 pm, Lee Sander <[EMAIL PROTECTED]> wrote:
> hi,
> i have a list and i can get elements form it via slicing
> L[start:stop]
> but sometimes the start is > stop i.e. I want to go in the opposite
> direction,eg
> L[10:2],
>
> mattab lets you do L(10:-1:2) to achive this, is there a way to do
> this in python?

>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
>>> a[3:10:2]
[4, 6, 8, 10]
>>> a[10:3:-2]
[11, 9, 7, 5]

> thanks
> L

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to C/C++

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 13:17:01 -0300, Blubaugh, David A.  
<[EMAIL PROTECTED]> escribió:

> Has anyone worked with a translator that will translate python to c/c++
> source code?  I know that there is already one translator of this nature
> (shedskin compiler) out there.  However, it is still in the beta stage
> of development.  Does anyone know of a more developed version of a
> translator of this nature?

There is also Cython (based on Pyrex). But they use a different approach  
than ShedSkin. You may want to read this thread:
http://thread.gmane.org/gmane.comp.compilers.shedskin.general/66

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread 7stud
On Mar 19, 2:40 am, grbgooglefan <[EMAIL PROTECTED]> wrote:
> Hi,
> I have a situation that I need to search a name in a big list of names
> in my Python embedded interpreter. I am planning to use hash map for
> quicker search.
> How do I create hash map in Python?
> Can you please guide me to some documentation or tutorial which
> provides information on creating, editing, searching through hash map
> in Python?
> Thanks.

#creating:
my_dict = {'a':1, 'b':2, 'c':3}

#editing:
my_dict['a'] = 10

#searching:
result = my_dict.get('a', None)
print result  //10

result = my_dict.get('f', None)
print result  //None
-- 
http://mail.python.org/mailman/listinfo/python-list


[newbie] using ElementTree, how to add doctype and xml pi

2008-03-19 Thread dave berk
Hi all

I have an svg file i'm creating on the fly. How do I add the doctype and xml
pi? They're not an element per se, and there is no function to add them. Am
I suppose to add them as elements after all?

I have something like this:

self.svgRoot = ET.Element("svg", xmlns=r'http://www.w3.org/2000/svg')
ET.SubElement(self.svgRoot, "g", transform="scale(1,-1)")



self.tree = ET.ElementTree(self.svgRoot)
...

thanks
dave
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: add new csv line

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 13:01:08 -0300, Alexandru Dumitrescu  
<[EMAIL PROTECTED]> escribió:

> Is there a way to add a new line at the beginning of  a  *.csv file,
> line which contain the name of the columns?

Once the file was written? You have to create another file, write the  
headings, and copy the data from the first one.

If you are asking how to do that with a csv.Writer object, just call  
writerow(list_of_column_names) before writing the data itself.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard

2008-03-19 Thread Graham Dumpleton
On Mar 19, 9:30 pm, geert <[EMAIL PROTECTED]> wrote:
> On Mar 19, 2:26 am, Graham Dumpleton <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > On Mar 19, 9:47 am, geert <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 18, 6:56 pm, geert <[EMAIL PROTECTED]> wrote:
>
> > > > On Mar 14, 1:15 pm, [EMAIL PROTECTED] wrote:
>
> > > > > look 
> > > > > athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d...
>
> > > > > There is a macpython list that you can consult 
> > > > > athttp://www.nabble.com/Python---pythonmac-sig-f2970.html
>
> > > > Just wanted to let you know that I've solved my problem. The solution
> > > > is to compile mysql using
>
> > > > MACOSX_DEPLOYMENT_TARGET=10.5 \
> > > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > > ./configure --disable-dependency-tracking  --enable-thread-safe-client
> > > > --prefix=/usr/local/mysql
>
> > > > You then go this way to get it running on your machine:
>
> > > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/
>
> > > > Then reinstall MySQLdb. Magic!
>
> > > > Geert
>
> > > Seems that I've yelled success to quickly. Everything's ok as long as
> > > I just run the django dev server, but moving to apache 
> > > throughmod_wsgibrings a well-known but less than comforting complaint:
>
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352):
> > > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/
> > > LN/LNApache.wsgi'., referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent
> > > call last):, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in
> > > __call__, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response =
> > > self.get_response(request), referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in
> > > get_response, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] response =
> > > middleware_method(request), referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line
> > > 13, in process_request, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] engine =
> > > __import__(settings.SESSION_ENGINE, {}, {}, ['']), 
> > > referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line
> > > 2, in , referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from
> > > django.contrib.sessions.models import Session, 
> > > referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5,
> > > in , referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] from django.db
> > > import models, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/db/__init__.py", line 17, in ,
> > > referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] backend =
> > > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {},
> > > {}, ['']), referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12,
> > > in , referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] raise
> > > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), 
> > > referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured:
> > > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/
> > > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no
> > > suitable image found.  Did find:, referer:http://localhost/images/
> > > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/
> > > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-
> > > tmp/_mysql.so: no matching architecture in universal wrapper, 
> > > referer:http://localhost/images/
>
> > Did you again confirm that running:
>
> >   file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-
> > macosx-10.5-i386.egg-tmp/_mysql.so
>
> > shows the .so having the required architectures, specifically what
> > Apache runs

slicing a list but in downward fashion

2008-03-19 Thread Lee Sander
hi,
i have a list and i can get elements form it via slicing
L[start:stop]
but sometimes the start is > stop i.e. I want to go in the opposite
direction,eg
L[10:2],

mattab lets you do L(10:-1:2) to achive this, is there a way to do
this in python?
thanks
L
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread John Machin
On Mar 20, 9:14 am, sturlamolden <[EMAIL PROTECTED]> wrote:
> On 19 Mar, 22:48, John Machin <[EMAIL PROTECTED]> wrote:
>
> > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's,
> > and is IMHO more readable than Paul's.
>
> Is a Python set implemented using a hash table?

What don't you understand about the comments in the first two
screenfuls of Objects/setobject.c?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv.Sniffer - delete in Python 3.0?

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 12:44:05 -0300, <[EMAIL PROTECTED]> escribió:

> The csv module contains a Sniffer class which is supposed to deduce the
> delimiter and quote character as well as the presence or absence of a  
> header
> in a sample taken from the start of a purported CSV file.  I no longer
> remember who wrote it, and I've never been a big fan of it.  It  
> determines
> the delimiter based almost solely on character frequencies.  It doesn't
> consider what the actual structure of a CSV file is or that delimiters  
> and
> quote characters are almost always taken from the set of punctuation or
> whitespace characters.  Consequently, it can cause some occasional
> head-scratching:
>
> >>> sample = """\
> ... abc8def
> ... def8ghi
> ... ghi8jkl
> ... """
> >>> import csv
> >>> d = csv.Sniffer().sniff(sample)
> >>> d.delimiter
> '8'
> >>> sample = """\
> ... a8bcdef
> ... ab8cdef
> ... abc8def
> ... abcd8ef
> ... """
> >>> d = csv.Sniffer().sniff(sample)
> >>> d.delimiter
> 'f'
>
> It's not clear to me that people use letters or digits very often as
> delimiters.  Both samples above probably represent data from  
> single-column
> files, not double-column files with '8' or 'f' as the delimiter.

I've seen an 'X' used as field separator - but in that case all values  
were numbers only.

> I would be happy to get rid of it in 3.0, but I'm also aware that some
> people use it.  I'd like feedback from the Python community about this.   
> If
> I removed it is there someone out there who wants it badly enough to
> maintain it in PyPI?

The Sniffer class already has a "delimiters" parameter; passing  
string.punctuation seems reasonable in case one wants to restrict the  
possible delimiter set. I think Sniffer is an useful class - but can't do  
magic, perhaps a few lines in the docs stating its limitations would be  
fine.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread John Machin
On Mar 20, 9:57 am, Justin Bozonier <[EMAIL PROTECTED]> wrote:
> On Mar 19, 2:48 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 19, 10:08 am, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> > > On 18 Mar, 23:45, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
> > > > > def nonunique(lst):
> > > > >slst = sorted(lst)
> > > > >dups = [s[0] for s in
> > > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))]
> > > > >return [dups[0]] + [s[1] for s in
> > > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))]
>
> > > > Argh!  What's wrong with something like:
>
> > > > def duplicates(l):
> > > > i = j = object()
> > > > for k in sorted(l):
> > > > if i != j == k: yield k
> > > > i, j = j, k
>
> > > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N)
> > > as opposed to ours which are O(N log N).
>
> > I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's,
> > and is IMHO more readable than Paul's.
>
> It's not as much O(N)... Paul Robin's uses a sort first which is
> definitely not O(N). Paul's could be prettied up a bit but the general
> principle is sound.

"""
from collections import defaultdict
def nonunique(lst):
   d = defaultdict(int)
   for x in lst: d[x] += 1
   return [x for x,n in d.iterkeys() if n > 1]
"""

I see no sort here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread Justin Bozonier
On Mar 19, 2:48 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Mar 19, 10:08 am, sturlamolden <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 18 Mar, 23:45, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
> > > > def nonunique(lst):
> > > >slst = sorted(lst)
> > > >dups = [s[0] for s in
> > > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))]
> > > >return [dups[0]] + [s[1] for s in
> > > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))]
>
> > > Argh!  What's wrong with something like:
>
> > > def duplicates(l):
> > > i = j = object()
> > > for k in sorted(l):
> > > if i != j == k: yield k
> > > i, j = j, k
>
> > Nice, and more readable. But I'd use Paul Robin's solution. It is O(N)
> > as opposed to ours which are O(N log N).
>
> I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's,
> and is IMHO more readable than Paul's.

It's not as much O(N)... Paul Robin's uses a sort first which is
definitely not O(N). Paul's could be prettied up a bit but the general
principle is sound.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: keeping state in an iterator object by rebinding next()

2008-03-19 Thread Terry Reedy

"Wilbert Berendsen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi,
|
| i am writing a simple parser, that generates tokens. The parser needs to
| maintain some state, because some parts of the file consist of different
| tokens. I thought the object could simply remember its state by assigning
| it's next() method to the method that is currently parsing. When the 
state
| changes, the called method rebinds next() and the next token will be 
returned
| by that function. Here's an example, proving that this indeed works.

For some undisclosed version.

| >>> class A:

I stronly suspect that if you make this a new-style class by adding 
'(object)',
this will not work.  See below.

| ...  def a(self):
| ...   self.next = self.b

This attaches the class attribute (method) b to the instance

| ...   return 1
| ...  def b(self):
| ...   self.next = self.a
| ...   return 2
| ...  def __iter__(self):
| ...   return self

Since A does not have a 'next' (or __next__, in 3.0), instances of A are 
not really iterators, under the new iterator protocol, and hence __iter__ 
above is not valid.  See below.

| ...
| >>> a=A()
| >>> a.a()
| 1
| >>> a.next()
| 2
| >>> a.next()
| 1
| >>> j=0
| >>> for i in a:

In 3.0a3, which uses new-style classes and iterator protocol, this croaks 
with
TypeError: iter() returned non-iterator of type 'A'

| ...  j += 1
| ...  if j > 10: break # prevent from running endlessly
| ...  print i

I suspect that this only works because the for-loop, not finding A.next, 
used the old iterate-by-index protocol and calls a.next with 0, 1, 2,  
To find out, put 'print self' inside methods a and b.

 ...
| 2
| 1
| 2
| 1
| 2
| 1
| 2
| 1
| 2
| 1
| >>>
|
| my question is: is this legal Python?

In whatever version you used, it seems to be, but not in the future.

| An iterator could save the next() method object,

You mean, the iterator user.

| and in that case it could stop working It works now, because
| apparently the for- construct resolves 'next' each time for the object 
before
| calling it.

A standard idiom for explicit iteration with a new style iterator and 
'while' would do just what you suggest.

itnext = iter(a).next
try:
while True
print itnext()
except StopIteration:
pass

| The other solution would be just jumping to the correct method from 
within the | next() method. But that gives an extra call...

Or, make a and b staticmethods, remove the self param, and make __iter__ a 
generator
  def __iter__(self):
while True:
  yield self.next()

The speed penalty of the indirection thru the generator is minimal.

Terry Jan Reedy



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: URLError

2008-03-19 Thread Steven D'Aprano
On Wed, 19 Mar 2008 14:45:39 -0700, Jim wrote:

> Program randomly aborts when looking up url. The program loop thru 
> 4000+ records looking
> up ID via internet and returns html code which is used in subsequent
> processing. The code
> for looking-up record is below followed by abort details. Can anyone
> help with catching the
> abort before program aborts or provide code to automatically start
> program? 


Yes. Wrap the offending code with a try...except loop, something similar 
to this.


try:
contents = urllib2.urlopen(url).read()
except URLError, e:
if e.errno == 10053:
# "Software caused connection abort"
response = raw_input(
"Temporary failure, Skip/Halt/try Again?")
response = response.lower().strip()
if response in ('h', 'halt'):
break
elif response in ('a', 'again', 't', 'try', 'try again'):
continue
elif response in ('', 's', 'skip'):
lines -= 1
continue
else:
print "Unknown response, boo hiss to you!"
raise


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing all instances of a certain value from a list

2008-03-19 Thread Hrvoje Niksic
Lee Sander <[EMAIL PROTECTED]> writes:

> Hi,
> I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
> many missing vlaues which are represented as None. I would like to
> remove all such instances in one go.
> There is a remove function but it removes only the first instance, is
> there a delete/remove all function?

No, but you can easily simulate it using, for example:

lst[:] = (el for el in lst if el is not None)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing all instances of a certain value from a list

2008-03-19 Thread BJörn Lindqvist
On Wed, Mar 19, 2008 at 10:28 PM, Lee Sander <[EMAIL PROTECTED]> wrote:
> Hi,
>  I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
>  many missing vlaues which are represented as None. I would like to
>  remove all such instances in one go.
>  There is a remove function but it removes only the first instance, is
>  there a delete/remove all function?
>  thanks

If it is ok to copy the list instead of mutating it, use a list comprehension:

>>> L = [-1.3, 1.22, 9.2, None, 2.3]
>>> [x for x in L if x is not None]
[-1.3, 1.22, 9.1993, 2.2998]

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Steven D'Aprano
On Wed, 19 Mar 2008 17:40:39 -0400, Nicholas F. Fabry wrote:

> To summarize my proposal VERY briefly:
> 
> 
> - Make aware datetime objects display in local time, but calculate/
> compare in UTC.

Your proposal is ambiguous. What does that mean? Can you give an example?




> - Raise exceptions when an illegal or ambiguous datetime is instantated.

You mean like they already do?

>>> datetime.datetime(2008, 03, 35)  # 35th of March
Traceback (most recent call last):
  File "", line 1, in 
ValueError: day is out of range for month




As for ambiguous, how can datetime arguments be ambiguous?

Help on class datetime in module datetime:

class datetime(date)
 |  datetime(year, month, day[, hour[, minute[, second[, 
 microsecond[,tzinfo])


What possible ambiguity is there?


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: printing dictionary and tuple

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 08:16:52 -0300, Beema shafreen  
<[EMAIL PROTECTED]> escribió:

> i am trying to print the dictionary values and tuple in a same line as  
> below
>
> print "\t".join(dict[a].values())+'\t'+"\t".join(b)
>
> Error I get is the  TypeError,
>  since i have  misisng values in the dictionary. if i use exception i  
> will
> miss those
> how should i print the data without missing the lines excluding the error
> separated by tab.

What is a? What is b? Their contents? I *guess* this is what you want:

a = {'some': 'values',
  3.14: 'in a',
  1234: 'dictionary'}
b = ('99', 'bottles', 'of', 'beer')
print '\t'.join(a.values()) + '\t' + '\t'.join(b)

The code above only works if all values are strings - else you could get a  
TypeError. In that case, convert all items to string before joining:

a = {'some': 'values',
  'in a': 3.14,
  'dictionary': 1234}
b = (99, 'bottles', 'of', 'beer')
print ('\t'.join([str(value) for value in a.values()])
+ '\t'
+ '\t'.join([str(item) for item in b]))

If this is not your problem, please provide a complete example next time,  
and the full exception traceback is very important too.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


removing all instances of a certain value from a list

2008-03-19 Thread Lee Sander
Hi,
I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
many missing vlaues which are represented as None. I would like to
remove all such instances in one go.
There is a remove function but it removes only the first instance, is
there a delete/remove all function?
thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ADO error - large data set

2008-03-19 Thread dsavitsk
Is it possible there is some bad data in the larger db? This is asinine, but 
maybe write a small script that adds some data, then opens and closes the 
db, then repeats this. If this is a size issue, then you can at least narrow 
it down to where the size limit is? And, if it isn't you should be able to 
figure that out, too. Otherwise, play around with the locking and cursor 
options.

-d


"Gyula" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi there,
>
> I have been running Python to tap into an MS Access 2003 database
> using ADO (PythonWin+COM). Everything works great creating recordsets
> etc. when I open a table with a small number of records. However, when
> I try to run the same Python code with a large table (>100,000) I get:
>
> Traceback (most recent call last):
>  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
> \scriptutils.py", line 310, in RunScript
>exec codeObject in __main__.__dict__
>  File "C:\Documents and Settings\user\Desktop\PythonWS\scripts
> \readmsaccess.py", line 43, in 
>rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3)
>  File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C-
> D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open
>, ActiveConnection, CursorType, LockType, Options)
> com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
> 5003251, -2147467259), None)
>
> The small and large table structures are identical, all I do is change
> the tblname from input1000 (1000 records) to input (>10 records).
> I use optimistic locking and keyset cursor..nothing out of the
> ordinary?
>
> Any ideas? ADO 2.8 is what I am using.
>
> Thanks a lot!
> GG 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread sturlamolden
On 19 Mar, 22:48, John Machin <[EMAIL PROTECTED]> wrote:

> I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's,
> and is IMHO more readable than Paul's.

Is a Python set implemented using a hash table?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Christian Heimes
Nicholas F. Fabry schrieb:
> Thank you for the prompt response and suggestion!  I am writing up a  
> proposal presently.  There are, however, two broad category of changes  
> - the 'easy' changes, which could be accomplished with little  
> additional effort, and the 'hard' changes, which would require  
> significant reworking of the datetime class (or a wrapper around it).   
> I was going to break my proposal up into two parts, the easy part and  
> the hard part.  Does that sound like a good idea?  Or should I unify  
> the two?  The prime purpose of all the changes, easy and hard, is to  
> make timezone handling accurate and clear, reduce and make clearer the  
> (application programmer) code required to use them, and give more  
> informaton to the programmer about errors, not silently assume  
> something and pass them.

Yes, it sounds like a good idea. The low hanging fruits (aka easy tasks) 
could be implemented for 2.6 and 3.0. The more complex tasks may have to 
wait for 2.7 and 3.1

Apropos time zones. A while ago I proposed the inclusion of pytz. But 
Stuart argued that the tz database may change monthly so I retracted my 
proposal. But Stuart has proposed some improvements for datetime's tz 
class. I suggest you contact him.

> Please clarify how long a novel is?  The problem with the modules are  
> not bugs, they are problems with real world use scenarios that result  
> in inescabably ugly code without improvements to the module - so the  
> explanations involve code samples and use cases... so they may be  
> 'long'.  Could you suggest a maximum number of (70 char) lines, or an  
> example of an overly long proposal?

Some people tend to start their postings like:

In the year 2008 after the birth of Christ I, the son of Jone, son of 
James ...

Do you get my point? :] I suggest you start with a short introduction of 
yourself and your proposal. Short paragraphs and short sentences are 
easier to read than long. You'll do fine ;)


Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this valid ?

2008-03-19 Thread John Machin
On Mar 20, 8:18 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> by accident I typed a double value test,
> and to my surprise it seems to work.
> Is this valid ?
>
> a = 2
> b = 2
>
> a == b == 2
>

Of course. You can chain comparisons as much as you like and is
(semi-)sensible, e.g.

assert 0 < thing_index < thing_count <= UTTER_MAX_NTHINGS

There was an interesting use of chained comparison within the last day
or 2 in a thread about deriving a set of duplicated list elements --
look for subject == "finding items that occur more than once in a
list" and author == "Arnaud Delobelle".

Cheers,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread Terry Reedy

"sturlamolden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On 19 Mar, 09:40, grbgooglefan <[EMAIL PROTECTED]> wrote:
|
| > How do I create hash map in Python?
|
| Python dictionaries are the fastest hash maps known to man.

If you only have keys (the names) and no values attached to them, then use 
a set. 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding items that occur more than once in a list

2008-03-19 Thread John Machin
On Mar 19, 10:08 am, sturlamolden <[EMAIL PROTECTED]> wrote:
> On 18 Mar, 23:45, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
> > > def nonunique(lst):
> > >slst = sorted(lst)
> > >dups = [s[0] for s in
> > > filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))]
> > >return [dups[0]] + [s[1] for s in
> > > filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))]
>
> > Argh!  What's wrong with something like:
>
> > def duplicates(l):
> > i = j = object()
> > for k in sorted(l):
> > if i != j == k: yield k
> > i, j = j, k
>
> Nice, and more readable. But I'd use Paul Robin's solution. It is O(N)
> as opposed to ours which are O(N log N).

I'd use Raymond Hettinger's solution. It is as much O(N) as Paul's,
and is IMHO more readable than Paul's.
-- 
http://mail.python.org/mailman/listinfo/python-list


URLError

2008-03-19 Thread Jim
Program randomly aborts when looking up url. The program loop thru
4000+ records looking
up ID via internet and returns html code which is used in subsequent
processing. The code
for looking-up record is below followed by abort details. Can anyone
help with catching the
abort before program aborts or provide code to automatically start
program? Currently, if
program is restarted the process starts after last good record but
must be restarted manually.

Thanks
Jim

code start here

#start lookups pass
while lines < 5000:
lines += 1
d =
ifile.read(8)

print str(lines) + ' ' + d
z = ifile.read(1)
f2 = b + d
h4 = h1+f2+h3#file name for
saving HMTL file
html_file = open(h4, 'w')
url  = a + d + c + b #build url to
lookup record in database
contents = urllib2.urlopen(url).read()   #lookup account in
database
soup = BeautifulSoup(contents)
html_file.write(soup.prettify()) #write HTML file
targetPage = soup.prettify()
targetHTML = targetPage  #set-up
record for edit pass
html_file.close()#close HTML file


abort details
==
429 90078431(note:this record 429 is where abort happen-when program
restarted this record processed normally)

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
  File "Lookup Records.py", line 77, in 
contents = urllib2.urlopen(url).read()
  File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 374, in open
response = self._open(req, data)
  File "C:\Python25\lib\urllib2.py", line 392, in _open
'_open', req)
  File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 1100, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python25\lib\urllib2.py", line 1075, in do_open
raise URLError(err)
URLError: 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Nicholas F. Fabry
On Mar 19, 2008, at 16:30, Christian Heimes wrote:

> Nicholas F. Fabry schrieb:
>> This is a query for information as to how to proceed.  I am not a   
>> professional programmer, but I use Python a great deal to help me  
>> in  my main job, which involves designing schedules for a global  
>> airline.   As such, I use datetime (and dateutil) extensively, and  
>> after much  use, I have come to some conclusions about their  
>> utility, and how to  improve them.  Some of these changes are quite  
>> minor and would result  in a large increase in utility (low hanging  
>> fruit), while some changes  are major, and would result in less  
>> obvious benefits - but these  changes would increase the 'Python  
>> Zen' of them.
>> So - where should I propose these changes?  Here?  python-dev?   
>> Should  I write up a full PEP or should I just give a more informal  
>> outline  with code samples?  I would volunteer to help maintain/ 
>> improve  datetime, but I don't speak C at all, unfortunately, and  
>> datetime  appears to be in C.
>
> Please write a detailed but not too long proposal to the Python  
> ideas mailing list. The proposal should explain how you like to  
> improve the datetime module. But *please* don't write a novel.  
> You'll get more attention when the signal to noise ratio is high. A  
> bullet list of features is easier to read than a long text block.
>

Thank you for the prompt response and suggestion!  I am writing up a  
proposal presently.  There are, however, two broad category of changes  
- the 'easy' changes, which could be accomplished with little  
additional effort, and the 'hard' changes, which would require  
significant reworking of the datetime class (or a wrapper around it).   
I was going to break my proposal up into two parts, the easy part and  
the hard part.  Does that sound like a good idea?  Or should I unify  
the two?  The prime purpose of all the changes, easy and hard, is to  
make timezone handling accurate and clear, reduce and make clearer the  
(application programmer) code required to use them, and give more  
informaton to the programmer about errors, not silently assume  
something and pass them.

I have to sign up for that mailing list - I will do so, and submit my  
ideas there.

Please clarify how long a novel is?  The problem with the modules are  
not bugs, they are problems with real world use scenarios that result  
in inescabably ugly code without improvements to the module - so the  
explanations involve code samples and use cases... so they may be  
'long'.  Could you suggest a maximum number of (70 char) lines, or an  
example of an overly long proposal?


> I'm a core developer and I may be interested in mentoring your  
> proposal. I can guide you through the process, review code and  
> commit it.
>

Thank you very much for the offer - I greatly appreciate it.  I must  
admit, my motivation is because Python made programming so much fun  
for me again (my first machine was a Sinclair ZX80, long, long ago),  
and I want to improve this part of the language so datetime  
calculations are clean and neat (like the rest of Python) and don't  
force programmers to manually go through what the library should do  
for them.


> Yes, the datetime module is written in C. But we may move the C code  
> to _datetime and create a facade module in Python.
>

That would be excellent for me, because the underlying datetime  
routines work correctly and quickly; it's the 'topmost' layer that  
needs to be improved to do the right thing.  And, I could then  
actually write/maintain the Python code in the facade module, rather  
than request someone else 'do it for me' in C.

To summarize my proposal VERY briefly:


- Make aware datetime objects display in local time, but calculate/ 
compare in UTC.

- Raise exceptions when an illegal or ambiguous datetime is instantated.


Thank you again,

Nick






> Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Script Request...

2008-03-19 Thread some one
Thanks Diez, I found some docs and examples on urllib2.  Now how do i 
search the string I get from urllib2, lets say I put it in "myURL", How 
do I search for only Numbers and ".'s" in the "#.#.#.#" pattern.  That 
is all I am interested in with all the data retrieved.  Just the IP 
Address from amongst a bunch of data that I have no use of currently.

I would I write a pattern matching function to extract only the IP 
address from "myURL"?

In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] 
says...
> some one wrote:
> 
> > Hi all, I am not to familiar with python yet and I am wondering if
> > someone can write a script that will monitor my DSL modems IP address
> > and notify when it changes, its a 2Wire Advanced DSL Modem.  I need to
> > know when it changes because I am trying to run my own inhouse server
> > and have to update my domain records through verio.com.
> > 
> > The script would need to read the text of a web page( on my modem the
> > address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and
> > search for a string containing the IP address.
> > 
> > Can anyone help?
> > thanks, I'll keep monitoring this thread.
> 
> Try urllib2 to fetch the data, use either string-search, regular expressions
> or even BeautifulSoup to extract the data. Use a cron-job to do that on a
> regular base or use module time.sleep() together with an endless loop to
> monitor that location periodically.
> 
> Show us your concrete efforts, and we will suggest improvements.
> 
> Diez
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this valid ?

2008-03-19 Thread Gary Herron
Stef Mientki wrote:
> hello,
>
> by accident I typed a double value test,
> and to my surprise it seems to work.
> Is this valid ?
>
> a = 2
> b = 2
>
> a == b == 2
>
> thanks,
> Stef Mientki
>
>   
Yes.  It's been in Python since the earliest days.  You usually see it 
in test like this:
  if a < b < c:
but any comparison operators work.  The meaning is the same as the AND 
of each individual test.

Gary Herron

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this valid ?

2008-03-19 Thread Mike Driscoll
On Mar 19, 4:18 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> by accident I typed a double value test,
> and to my surprise it seems to work.
> Is this valid ?
>
> a = 2
> b = 2
>
> a == b == 2
>
> thanks,
> Stef Mientki

It sure looks that way...

See http://www.python.org/doc/2.3.5/ref/comparisons.html for more
info.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Fate of the repr module in Py3.0

2008-03-19 Thread Raymond Hettinger
Was looking at PEP 3108, http://www.python.org/dev/peps/pep-3108/ ,
and saw that the repr module was slated for vaporization.  I've only
used the module a few times ever.  I'm curious if the community wants
it kept around or whether it is considered clutter.

The PEP is going to be finalized soon, so if you have issues with it,
they should be sent to the PEP author or brought up on the list,
http://mail.python.org/mailman/listinfo/stdlib-sig .

Raymond
-- 
http://mail.python.org/mailman/listinfo/python-list


Is this valid ?

2008-03-19 Thread Stef Mientki
hello,

by accident I typed a double value test,
and to my surprise it seems to work.
Is this valid ?

a = 2
b = 2

a == b == 2

thanks,
Stef Mientki

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: keeping state in an iterator object by rebinding next()

2008-03-19 Thread Peter Otten
Wilbert Berendsen wrote:

> Hi,
> 
> i am writing a simple parser, that generates tokens. The parser needs to
> maintain some state, because some parts of the file consist of different
> tokens. I thought the object could simply remember its state by assigning
> it's next() method to the method that is currently parsing. When the state
> changes, the called method rebinds next() and the next token will be
> returned by that function. Here's an example, proving that this indeed
> works.
> 
 class A:
> ...  def a(self):
> ...   self.next = self.b
> ...   return 1
> ...  def b(self):
> ...   self.next = self.a
> ...   return 2
> ...  def __iter__(self):
> ...   return self
> ...
 a=A()
 a.a()
> 1
 a.next()
> 2
 a.next()
> 1
 j=0
 for i in a:
> ...  j += 1
> ...  if j > 10: break # prevent from running endlessly
> ...  print i
> ...
> 2
> 1
> 2
> 1
> 2
> 1
> 2
> 1
> 2
> 1

> 
> my question is: is this legal Python? An iterator could save the next()
> method object, and in that case it could stop working It works now,
> because apparently the for- construct resolves 'next' each time for the
> object before calling it.
> 
> The other solution would be just jumping to the correct method from within
> the next() method. But that gives an extra call...

It doesn't work with newstyle classes though as next() is looked up in the
class rather than the instance, just like the __xxx__() methods:

>>> class A(object):
... def __iter__(self): return self
... def next(self): return "class-next()"
...
>>> a = A()
>>> a.next = lambda: "instance-next()"
>>> a.next()
'instance-next()'
>>> from itertools import islice
>>> for item in islice(a, 3): print item
...
class-next()
class-next()
class-next()

Without the class-next() it isn't even recognized as an iterator

>>> del A.next
>>> for item in a: pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: iter() returned non-iterator of type 'A'

even though the instance-next() is still there:

>>> a.next()
'instance-next()'

So I recommend that you avoid that can of worms and go with the extra
indirection.

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread sturlamolden
On 19 Mar, 09:44, Torsten Bronger <[EMAIL PROTECTED]>
wrote:

> Could you elaborate on this?  (Sincere question; I have almost no
> idea of Haskell.)

If you already know Python, you will find Whitespace just as useful as
Haskell.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Prototype OO

2008-03-19 Thread Marc 'BlackJack' Rintsch
On Wed, 19 Mar 2008 17:59:40 +0100, sam wrote:

> Can someone tell me why class-based OO is better that Prototype based, 
> especially in scripting langage with dynamic types as Python is?

Is it better!?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Christian Heimes
Nicholas F. Fabry schrieb:
> This is a query for information as to how to proceed.  I am not a  
> professional programmer, but I use Python a great deal to help me in  
> my main job, which involves designing schedules for a global airline.   
> As such, I use datetime (and dateutil) extensively, and after much  
> use, I have come to some conclusions about their utility, and how to  
> improve them.  Some of these changes are quite minor and would result  
> in a large increase in utility (low hanging fruit), while some changes  
> are major, and would result in less obvious benefits - but these  
> changes would increase the 'Python Zen' of them.
> 
> So - where should I propose these changes?  Here?  python-dev?  Should  
> I write up a full PEP or should I just give a more informal outline  
> with code samples?  I would volunteer to help maintain/improve  
> datetime, but I don't speak C at all, unfortunately, and datetime  
> appears to be in C.

Please write a detailed but not too long proposal to the Python ideas 
mailing list. The proposal should explain how you like to improve the 
datetime module. But *please* don't write a novel. You'll get more 
attention when the signal to noise ratio is high. A bullet list of 
features is easier to read than a long text block.

I'm a core developer and I may be interested in mentoring your proposal. 
I can guide you through the process, review code and commit it.

Yes, the datetime module is written in C. But we may move the C code to 
_datetime and create a facade module in Python.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomaly in time.clock()

2008-03-19 Thread John Machin
On Mar 19, 11:17 pm, Godzilla <[EMAIL PROTECTED]> wrote:
> Hi John,
>
> I am using time.clock to calculate the elapsed time. Below is an
> example of what I was trying to do:
>
> import time
> import thread

Silly me, not being able to infer that from your initial post!

[snip]
>
> But the time.clock() sometimes return a value of between -3.5 to -4.5
> seconds backward. Note that not all computers are behaving the same. I
> have not experience the same problem with the computer at home.

Same "service pack" number?

Your code "worked" (no time warp) for me on a single-core AMD Turion64
CPU running (32 bit) Windows XP Service Pack 2 Build 2600. Maybe the
ones that "fail" have dual-core CPUs.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Mac programs from Python instead of from AppleScript

2008-03-19 Thread Kevin Walzer
[EMAIL PROTECTED] wrote:
> When I'm running Script Editor, I can get Maya to draw a sphere by
> typing:
> 
> tell application "Maya"
>   execute "sphere"
> end tell
> 
> When I try this using Python, I get this error message:
> 
> IDLE 1.2.2
 app('Maya').execute('sphere')
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> app('Maya').execute('sphere')
> NameError: name 'app' is not defined
> 
> Maybe I need to load some libraries first.
> 
> Please help me to get started.
> 
> Thanks
>  Dewey V. Schorre
> 

Take a look at appscript:

http://appscript.sourceforge.net/

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Search the command history - Python Shell

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 07:07:50 -0300, Tim Chase  
<[EMAIL PROTECTED]> escribió:

>> Are there any simillar key combination in Python Shell like Linux Ctrl+R
>> (reverse-i-search) to search the command history?
>
> It must depend on how your version of Python was built...mine
> here on my Linux box has exactly that functionality.  I press ^R
> and start typing, and the line comes up from my typed history.

On Windows you would type a few characters and use F8 and Shift-F8, or F7  
to choose from a pop-up list.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv dictreader

2008-03-19 Thread Mike Driscoll
On Mar 19, 1:55 pm, brnstrmrs <[EMAIL PROTECTED]> wrote:
> On Mar 19, 2:32 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 19, 1:06 pm, brnstrmrs <[EMAIL PROTECTED]> wrote:
>
> > > I am trying to use the dictionary reader to import the data from a csv
> > > file and create a dictnary from it but just can't seem to figure it
> > > out.
>
> > > Here is my code:
>
> > > >>>import csv
> > > >>>reader = csv.DictReader(open('table.csv'))
> > > >>>for row in reader:
> > > >>>print row
>
> > > my csv files looks like this:
>
> > > Bytecode,Element
> > > \x00\x00,
> > > \x01\x00,0001
> > > 
> > > \x09\x00,0009
>
> > > My output shows:
> > > {'Bytecode': '\\x00\\x00', 'Element': ''}
> > > {'Bytecode': '\\x01\\x00', 'Element': '0001'}
> > > ...
> > > {'Bytecode': '\\x09\\x00', 'Element': '0009'}
>
> > > 1. how can I get access to this directory
>
> > What do you mean? You can get each element in the dict by doing this:
>
> > for row in reader:
> > print row['Bytecode']
> > print row['Element']
>
> > > 2. why does the values come with two backslashs infront of the "x"
>
> > The double back slash is for escaping purposes, I think. If you print
> > this: '\\x09\\x00'
> > you'll get this:  \x09\x00
>
> > Mike
>
> Thanks.  It works for the Bytecode but when I do print row['Element']
> I get a error messageprint row['Element'] KeyError: 'Element'

That's weird. Since I only had your output, I did the following:



reader = [ {'Bytecode': '\\x00\\x00', 'Element': ''},{'Bytecode':
'\\x01\\x00', 'Element': '0001'} ]

for x in reader:
print x['Element']
print x['Bytecode']



\x00\x00
0001
\x01\x00



I must be missing something...

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Calling Mac programs from Python instead of from AppleScript

2008-03-19 Thread dvschorre
When I'm running Script Editor, I can get Maya to draw a sphere by
typing:

tell application "Maya"
execute "sphere"
end tell

When I try this using Python, I get this error message:

IDLE 1.2.2
>>> app('Maya').execute('sphere')

Traceback (most recent call last):
  File "", line 1, in 
app('Maya').execute('sphere')
NameError: name 'app' is not defined
>>>

Maybe I need to load some libraries first.

Please help me to get started.

Thanks
 Dewey V. Schorre

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to solve a three-element equation set?

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 04:05:50 -0300, purple <[EMAIL PROTECTED]> escribió:

> Could you guys do me a favor for solving a equation set?
>
> Z=d/4*(1-SIN(X)/X)
> X=8q/(D^2*Y)+SIN(X)
> Y=1/n*Z^(2/3)*i^(1/2)
>
> In this equation set, X,Y&Z are the unkown parameters, the others say,
> d, q, n&i are known. SO in python, how to program it to represent X, Y
> and Z in the form of d, q, n and i?

You want a numeric result, I presume. SciPy www.scipy.org has several  
minimization functions.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


keeping state in an iterator object by rebinding next()

2008-03-19 Thread Wilbert Berendsen
Hi,

i am writing a simple parser, that generates tokens. The parser needs to 
maintain some state, because some parts of the file consist of different 
tokens. I thought the object could simply remember its state by assigning 
it's next() method to the method that is currently parsing. When the state 
changes, the called method rebinds next() and the next token will be returned 
by that function. Here's an example, proving that this indeed works.

>>> class A:
...  def a(self):
...   self.next = self.b
...   return 1
...  def b(self):
...   self.next = self.a
...   return 2
...  def __iter__(self):
...   return self
...
>>> a=A()
>>> a.a()
1
>>> a.next()
2
>>> a.next()
1
>>> j=0
>>> for i in a:
...  j += 1
...  if j > 10: break   # prevent from running endlessly
...  print i
...
2
1
2
1
2
1
2
1
2
1
>>>

my question is: is this legal Python? An iterator could save the next() method 
object, and in that case it could stop working It works now, because 
apparently the for- construct resolves 'next' each time for the object before 
calling it.

The other solution would be just jumping to the correct method from within the 
next() method. But that gives an extra call...


Met vriendelijke groet,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
-- Mahatma Gandi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: automatically doing some cleaning-up by the process when the systems shuts down

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 04:28:19 -0300, bharath venkatesh  
<[EMAIL PROTECTED]> escribió:

> handling SIGTERM allowed me to do cleaning up  while the system shuts  
> down
> but as i mentioned previously how can my  process know if the   system  
> was
> not shut down properly previously

Sorry about the confusion, I meant SIGTERM instead of SYSTERM.
Create a file with a known fixed name when the daemon starts, and remove  
it after a clean shutdown (you may want to write the daemon's PID). If the  
file already exists the next time it starts, that means that a clean  
shutdown was not performed.
(Note that this, and the previous question, are not specific to Python)

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter.Text widget - how to get text cursor position?

2008-03-19 Thread Alex9968
Alex9968 wrote:
> Is it possible to get position (in numbers) of the insertion cursor? As 
> I understood, Text widget uses mark named INSERT to store it, which is 
> available globally by just referencing INSERT, but how could I get 
> actual coordinate numbers of the mark?
> I need this because I want not just to insert string at, but to examine 
> text before and after the insertion cursor. I can probably use .get() to 
> extract the halves of text before and after cursor, but it'd be better 
> just to know the position.
>
> Thanks
It's .index()

Problem was that it's missed in Tkinter reference: a GUI for Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv dictreader

2008-03-19 Thread brnstrmrs
On Mar 19, 2:32 pm, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Mar 19, 1:06 pm, brnstrmrs <[EMAIL PROTECTED]> wrote:
>
>
>
> > I am trying to use the dictionary reader to import the data from a csv
> > file and create a dictnary from it but just can't seem to figure it
> > out.
>
> > Here is my code:
>
> > >>>import csv
> > >>>reader = csv.DictReader(open('table.csv'))
> > >>>for row in reader:
> > >>>print row
>
> > my csv files looks like this:
>
> > Bytecode,Element
> > \x00\x00,
> > \x01\x00,0001
> > 
> > \x09\x00,0009
>
> > My output shows:
> > {'Bytecode': '\\x00\\x00', 'Element': ''}
> > {'Bytecode': '\\x01\\x00', 'Element': '0001'}
> > ...
> > {'Bytecode': '\\x09\\x00', 'Element': '0009'}
>
> > 1. how can I get access to this directory
>
> What do you mean? You can get each element in the dict by doing this:
>
> for row in reader:
> print row['Bytecode']
> print row['Element']
>
> > 2. why does the values come with two backslashs infront of the "x"
>
> The double back slash is for escaping purposes, I think. If you print
> this: '\\x09\\x00'
> you'll get this:  \x09\x00
>
> Mike

Thanks.  It works for the Bytecode but when I do print row['Element']
I get a error messageprint row['Element'] KeyError: 'Element'
-- 
http://mail.python.org/mailman/listinfo/python-list


Inserting DTD statement to XML

2008-03-19 Thread [EMAIL PROTECTED]
I am new to Python and I am writing a script to build a XML document
and post it to a website.  I have a working script but need to insert
a DTD statement in my XML document and can't find out how to do this.
I am using "from xml.dom.minidom import Document"

Some code I am using is:

doc = Document()
rootNode = doc.createElement("employees")
doc.appendChild(rootNode )

I get the following when I print it out



   ...


What I would like is to have something like:




   ...


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv dictreader

2008-03-19 Thread Mike Driscoll
On Mar 19, 1:06 pm, brnstrmrs <[EMAIL PROTECTED]> wrote:
> I am trying to use the dictionary reader to import the data from a csv
> file and create a dictnary from it but just can't seem to figure it
> out.
>
> Here is my code:
>
> >>>import csv
> >>>reader = csv.DictReader(open('table.csv'))
> >>>for row in reader:
> >>>print row
>
> my csv files looks like this:
>
> Bytecode,Element
> \x00\x00,
> \x01\x00,0001
> 
> \x09\x00,0009
>
> My output shows:
> {'Bytecode': '\\x00\\x00', 'Element': ''}
> {'Bytecode': '\\x01\\x00', 'Element': '0001'}
> ...
> {'Bytecode': '\\x09\\x00', 'Element': '0009'}
>
> 1. how can I get access to this directory

What do you mean? You can get each element in the dict by doing this:

for row in reader:
print row['Bytecode']
print row['Element']


> 2. why does the values come with two backslashs infront of the "x"

The double back slash is for escaping purposes, I think. If you print
this: '\\x09\\x00'
you'll get this:  \x09\x00

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: modules devoted to manipulationg .reg files

2008-03-19 Thread Mike Driscoll
On Mar 19, 1:14 pm, black_13 <[EMAIL PROTECTED]> wrote:
> are there any python modules for manipulation of .reg files producted
> by
> the win32 prog "reg".
> thanks.
> black_13

The *.reg files are text files, so you can parse them like any text
file. You can just edit the Windows Registry directly using the built-
in module: _winreg. There's also a more abstract wrapper called YARW.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to get __thismodule__?

2008-03-19 Thread benhoyt
Wow -- thanks, guys. And who said Python only gives you one way to do
things. :-)  Metaclasses, globals(), and __subclasses__. Thank Duncan
for the __subclassess__ tip -- I didn't know about that.

I'd totally overlooked globals(). It's exactly what I was looking for
-- thanks, Peter. And I like your is_true_subclass() helper function
too.

I must say, I found it a bit weird that the first argument to
issubclass() *has* to be a class. I would have thought issubclass(42,
MyClass) would simply return False, because 42 is definitely not a
subclass of MyClass. But I guess "explicit is better than implicit",
and being implicit here might mask bugs.

globals() feels like the "right" way to do what I want -- fairly
simple and direct. Metaclasses are cool, but probably a touch too
complicated for this. And __subclassess__ seems a bit undocumented and
perhaps implementation-defined.

Cheers,
Ben.
-- 
http://mail.python.org/mailman/listinfo/python-list


modules devoted to manipulationg .reg files

2008-03-19 Thread black_13
are there any python modules for manipulation of .reg files producted
by
the win32 prog "reg".
thanks.
black_13
-- 
http://mail.python.org/mailman/listinfo/python-list


csv dictreader

2008-03-19 Thread brnstrmrs
I am trying to use the dictionary reader to import the data from a csv
file and create a dictnary from it but just can't seem to figure it
out.

Here is my code:
>>>import csv
>>>reader = csv.DictReader(open('table.csv'))
>>>for row in reader:
>>>print row

my csv files looks like this:

Bytecode,Element
\x00\x00,
\x01\x00,0001

\x09\x00,0009

My output shows:
{'Bytecode': '\\x00\\x00', 'Element': ''}
{'Bytecode': '\\x01\\x00', 'Element': '0001'}
...
{'Bytecode': '\\x09\\x00', 'Element': '0009'}

1. how can I get access to this directory
2. why does the values come with two backslashs infront of the "x"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove suffix from filename

2008-03-19 Thread Larry Bates
royG wrote:
> hi
> when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
> two.jpg'] etc i want to extract the
> basename without the suffix...ie i want to get 'one','two' etc and not
> 'one.jpg'
> 
> is there a function in python to do this or do i have tosplit it ..?
> thanks
> RG

import os

fname='F:/mydir/two.jpg'
filenameonly=os.path.splitext(os.path.basename(fname))[0]

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml sax

2008-03-19 Thread Robert Bossy
Timothy Wu wrote:
> Hi,
>
> I am using  xml.sax.handler.ContentHandler to parse some simple xml.
>
> I want to detect be able to parse the content of this tag embedded in 
> the XML.
> 174
>
>
> Is the proper way of doing so involving finding the "Id" tag 
> from startElement(), setting flag when seeing one, and in characters(),
> when seeing that flag set, save the content?
>
> What if multiple tags of the same name are nested at different levels
>
> and I want to differentiate them? I would be setting a flag for each level.
> I can imagine things get pretty messy when flags are all around.
>   
Hi,

You could have a list of all opened elements from the root to the 
innermost. To keep such a list, you append the name of the element to 
this stack at the end of startElement() and pop it off at the end of 
endElement().

In this way you have acces to the path of the current parser position. 
In order to differentiate between character data in Id and in Id/Id, you 
just have to iterate at the last elements of the list.

Cheers,
RB
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter.Text widget - how to get text cursor position?

2008-03-19 Thread Alex9968
Is it possible to get position (in numbers) of the insertion cursor? As 
I understood, Text widget uses mark named INSERT to store it, which is 
available globally by just referencing INSERT, but how could I get 
actual coordinate numbers of the mark?
I need this because I want not just to insert string at, but to examine 
text before and after the insertion cursor. I can probably use .get() to 
extract the halves of text before and after cursor, but it'd be better 
just to know the position.

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomaly in time.clock()

2008-03-19 Thread Ross Ridge
Godzilla  <[EMAIL PROTECTED]> wrote:
>But the time.clock() sometimes return a value of between -3.5 to -4.5
>seconds backward.

There are race conditions in your code.  In between the time you execute
"curTime = time.clock()" and calculate "curTime - self.timeStamp" in one
thread, the other thread can execute "self.timeStamp = time.clock()".
It's the only way your example program can print a negative "Actual
Elapsed Time" value.  The race condition seems unlikely, and it's hard
to explain how this could result in it printing a value in the range
of -3.5 to -4.5.  However, a race condition occuring between the two
evaluations of "curTime - self.timeStamp" is the only way your example
program could print a negative value.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Python to C/C++

2008-03-19 Thread Patrick Mullen
(sorry michael, didn't mean to personal post

On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote:
 > I think py2exe does this, but it might be a bit bloated

 No, py2exe basically bundles the main script and the interpreter
 together so it's easy to run and requires no python installation.

 Look into pyrex and pypy.  A mature translator doesn't exist.  Also
 there is ctypes which goes in reverse letting you use more c from
 python easily.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an XML DOM while offline?

2008-03-19 Thread Paul Boddie
On 19 Mar, 16:27, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> william tanksley wrote:
> > I want to parse my iTunes Library xml. All was well, until I unplugged
> > and left for the train (where I get most of my personal projects
> > done). All of a sudden, I discovered that apparently the presence of a
> > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
> > the Internet... So suddenly I was unable to do any work.

The desire to connect to the Internet for DTDs is documented in the
following bug:

http://bugs.python.org/issue2124

However, I can't reproduce the problem using xml.dom.minidom.parse/
parseString and plain XHTML, although I may be missing something which
activates the retrieval of the DTD.

> > I don't want to modify the iTunes XML; iTunes rewrites it too often.
> > How can I prevent xml.dom.minidom from dying when it can't access the
> > Internet?
>
> > Is there a simpler way to read the iTunes XML? (It's merely a plist,
> > so the format is much simpler than general XML.)
>
> Normally, this should be solved using an entity-handler that prevents the
> remote fetching. I presume the underlying implementation of a SAX-parser
> does use one, but you can't override that (at least I didn't find anything
> in the docs)

There's a lot of complicated stuff in the xml.dom package, but I found
that the DOMBuilder class (in xml.dom.xmlbuilder) probably contains
the things which switch such behaviour on or off. That said, I've
hardly ever used the most formal DOM classes to parse XML in Python
(where you get the DOM implementation and then create other factory
classes - it's all very "Java" in nature), so the precise incantation
is unknown/forgotten to me.

> The most pragmatic solution would be to rip the doctype out using simple
> string methods and/or regexes.

Maybe, but an example fragment of the XML might help us diagnose the
problem, ideally with some commentary from the people who wrote the
xml.dom software in the first place.

Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using threads in python is safe ?

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 04:43:34 -0300, Deepak Rokade <[EMAIL PROTECTED]>  
escribió:

> Thanks all for removing confusion about GIL,
> one more question;
> If jobs to be processed by threds is I/O bound would multithreading help
> python to improve speed of application ?
> Since I read that " multithreading is not a good strategy to improve  
> speed
> of python application."

Try and see what happens in your specific case. People keeps saying that  
but I've never seen conclusive evidence on this topic. Using several  
threads for I/O bound tasks seems reasonable to me, and is the easiest  
approach. For CPU bound tasks, multiple threads won't help much, be it  
Python or another language.
I mean, a reasonable number of threads with a reasonable task load. A  
server handling thousands of simultaneous connections is another beast.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Starting Out

2008-03-19 Thread Peter Decker
On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop <[EMAIL PROTECTED]> wrote:
> Hi, I would like to start using Python, but am unsure where to begin.
>  I know how to look up a tutorial and learn the language, but not what
>  all technologies to use.  I saw references to plain Python, Django,
>  and other things.
>
>  I want to use it for web building with database access.  What do I use
>  for that?  Does it matter what I use on the client side (mootools, or
>  whatever)?

If you are going to be developing web applications, there are many
excellent frameworks available, all of which provide database support.
If you are looking to develop desktop applications, you should check
out Dabo (http://dabodev.com). They integrate data access and GUI
controls, making it simple to create database apps. They use wxPython
for the UI layer, but hide all of its ugliness, allowing you to
program to a clean, consistent API for your GUI.


-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Latest updates inSQL server and other programming laguages like C++/Java

2008-03-19 Thread Gokul
The latest developments in SQL server 2008 and an complete
encyclopedia of microsoft softwares. Know the methodology to capture
customers requirements for new products. Get the latest development in
C++ and other IT related tools. A complete tutor for all your IT
needs. Visit

http://www.sqlserversoftware.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Prototype OO

2008-03-19 Thread sam

Some time ago (2004) there were talks about prototype-based languages and 
Prothon emerged.

Can someone tell me why class-based OO is better that Prototype based, 
especially in scripting langage with dynamic types as Python is?


Here are some links:

http://c2.com/cgi/wiki?PrototypeBasedProgramming
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Class-Based_vs._Prototype-Based_Languages



--
UFO Occupation
www.totalizm.pl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: csv.Sniffer - delete in Python 3.0?

2008-03-19 Thread Robin Becker
[EMAIL PROTECTED] wrote:

> 
> I would be happy to get rid of it in 3.0, but I'm also aware that some
> people use it.  I'd like feedback from the Python community about this.  If
> I removed it is there someone out there who wants it badly enough to
> maintain it in PyPI?
..
sounds like we really need

import ai

info = ai.guess_what_this_is('crummy.csv')

but I suspect that won't arrive before py5000

I use csv, but almost always with tab or comma separation and \r\n line 
terminators.
-- 
Robin Becker

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to C/C++

2008-03-19 Thread Michael Wieher
I think py2exe does this, but it might be a bit bloated

2008/3/19, Blubaugh, David A. <[EMAIL PROTECTED]>:
>
>  To All,
>
> Has anyone worked with a translator that will translate python to c/c++
> source code?  I know that there is already one translator of this nature 
> (shedskin
> compiler) out there.  However, it is still in the beta stage of
> development.  Does anyone know of a more developed version of a translator
> of this nature?
>
> Thanks,
>
> David Blubaugh
>
> This e-mail transmission contains information that is confidential and may
> be privileged.   It is intended only for the addressee(s) named above. If
> you receive this e-mail in error, please do not read, copy or disseminate it
> in any manner. If you are not the intended recipient, any disclosure,
> copying, distribution or use of the contents of this information is
> prohibited. Please reply to the message immediately by informing the sender
> that the message was misdirected. After replying, please erase it from your
> computer system. Your assistance in correcting this error is appreciated.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: url validator in python

2008-03-19 Thread Tim Chase
> How can I check the validity of absolute urls with http scheme?
> example:
> "http://www.example.com/something.html"; -> valid
> "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid

You could try something like

   import urllib
   tests = (
 ("http://www.google.com/ + Brite_AB_Iframe_URL + ", False),
 ("http://www.example.com/something.html";, True),
 ("https://www.google.com/ + Brite_AB_Iframe_URL + ", False),
 ("https://www.example.com/something.html";, True),
   )
   def no_method(url):
 if ':' in url[:7]:
   # strip off the leading http:
   return url.split(':', 1)[1]
 return url

   def is_valid_url(url):
 url = no_method(url)
 return url == urllib.quote(url)

   for test_url, expected_result in tests:
 print "Testing %s\nagainst %s" % (
   no_method(test_url),
   urllib.quote(no_method(test_url))
   )
 actual_result = is_valid_url(test_url)
 print 'Pass: %s' % (actual_result == expected_result)
 print '='*70

The reason for the no_method() is that otherwise it gets 
normalized to "http%3A//..." so you have to strip off that bit 
before comparing.

-tkc




-- 
http://mail.python.org/mailman/listinfo/python-list


Python to C/C++

2008-03-19 Thread Blubaugh, David A.
To All,


Has anyone worked with a translator that will translate python to c/c++
source code?  I know that there is already one translator of this nature
(shedskin compiler) out there.  However, it is still in the beta stage
of development.  Does anyone know of a more developed version of a
translator of this nature?   

Thanks,

David Blubaugh

This e-mail transmission contains information that is confidential and may be 
privileged.   It is intended only for the addressee(s) named above. If you 
receive this e-mail in error, please do not read, copy or disseminate it in any 
manner. If you are not the intended recipient, any disclosure, copying, 
distribution or use of the contents of this information is prohibited. Please 
reply to the message immediately by informing the sender that the message was 
misdirected. After replying, please erase it from your computer system. Your 
assistance in correcting this error is appreciated.


-- 
http://mail.python.org/mailman/listinfo/python-list

ADO error - large data set

2008-03-19 Thread Gyula
Hi there,

I have been running Python to tap into an MS Access 2003 database
using ADO (PythonWin+COM). Everything works great creating recordsets
etc. when I open a table with a small number of records. However, when
I try to run the same Python code with a large table (>100,000) I get:

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Documents and Settings\user\Desktop\PythonWS\scripts
\readmsaccess.py", line 43, in 
rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3)
  File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C-
D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open
, ActiveConnection, CursorType, LockType, Options)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
5003251, -2147467259), None)

The small and large table structures are identical, all I do is change
the tblname from input1000 (1000 records) to input (>10 records).
I use optimistic locking and keyset cursor..nothing out of the
ordinary?

Any ideas? ADO 2.8 is what I am using.

Thanks a lot!
GG
-- 
http://mail.python.org/mailman/listinfo/python-list


add new csv line

2008-03-19 Thread Alexandru Dumitrescu
Hello everybody,
Is there a way to add a new line at the beginning of  a  *.csv file,
line which contain the name of the columns?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to remove suffix from filename

2008-03-19 Thread Mel
royG wrote:
> when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
> two.jpg'] etc i want to extract the
> basename without the suffix...ie i want to get 'one','two' etc and not
> 'one.jpg'
> 
> is there a function in python to do this or do i have tosplit it ..?
> thanks

os.path.splitext is the one, it think.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread sturlamolden
On 19 Mar, 09:40, grbgooglefan <[EMAIL PROTECTED]> wrote:

> How do I create hash map in Python?

Python dictionaries are the fastest hash maps known to man.

If you need persistent storage of your hash map, consider module bsddb
or dbhash.
-- 
http://mail.python.org/mailman/listinfo/python-list


how to remove suffix from filename

2008-03-19 Thread royG

hi
when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
two.jpg'] etc i want to extract the
basename without the suffix...ie i want to get 'one','two' etc and not
'one.jpg'

is there a function in python to do this or do i have tosplit it ..?
thanks
RG
-- 
http://mail.python.org/mailman/listinfo/python-list


url validator in python

2008-03-19 Thread vvangelovski
How can I check the validity of absolute urls with http scheme?
example:
"http://www.example.com/something.html"; -> valid
"http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid
-- 
http://mail.python.org/mailman/listinfo/python-list


csv.Sniffer - delete in Python 3.0?

2008-03-19 Thread skip

The csv module contains a Sniffer class which is supposed to deduce the
delimiter and quote character as well as the presence or absence of a header
in a sample taken from the start of a purported CSV file.  I no longer
remember who wrote it, and I've never been a big fan of it.  It determines
the delimiter based almost solely on character frequencies.  It doesn't
consider what the actual structure of a CSV file is or that delimiters and
quote characters are almost always taken from the set of punctuation or
whitespace characters.  Consequently, it can cause some occasional
head-scratching:

>>> sample = """\
... abc8def
... def8ghi
... ghi8jkl
... """
>>> import csv
>>> d = csv.Sniffer().sniff(sample)
>>> d.delimiter
'8'
>>> sample = """\
... a8bcdef
... ab8cdef
... abc8def
... abcd8ef
... """
>>> d = csv.Sniffer().sniff(sample)
>>> d.delimiter
'f'

It's not clear to me that people use letters or digits very often as
delimiters.  Both samples above probably represent data from single-column
files, not double-column files with '8' or 'f' as the delimiter.

I would be happy to get rid of it in 3.0, but I'm also aware that some
people use it.  I'd like feedback from the Python community about this.  If
I removed it is there someone out there who wants it badly enough to
maintain it in PyPI?

Thanks,

-- 
Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cx_Oracle execute procedure

2008-03-19 Thread Poppy
Thanks Jerry and Diez. The first two replies I found answered my noob 
question.


"Jerry Hill" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Wed, Mar 19, 2008 at 11:03 AM, Poppy <[EMAIL PROTECTED]> 
> wrote:
>> I've been working on the code below and and executes silently, no
>>  complaints, however the end result should be a record in my table and 
>> it's
>>  not added. The procedure works with the passed credentials using SQLPlus 
>> or
>>  SQL Developer clients. However I'm not sure if I'm constructing my 
>> python
>>  code correctly to interact with Oracle.
> ...
>>  connection.commit
>>  cur.close
>>  connection.close
>
> You have to actually call these methods:
> connection.commit()
> cur.close()
> connection.close()
>
> Without the parentheses, you're just getting a reference to the
> methods and immediately discarding them.
>
> -- 
> Jerry 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cx_Oracle execute procedure

2008-03-19 Thread Diez B. Roggisch
Poppy wrote:

> I've been working on the code below and and executes silently, no
> complaints, however the end result should be a record in my table and it's
> not added. The procedure works with the passed credentials using SQLPlus
> or SQL Developer clients. However I'm not sure if I'm constructing my
> python code correctly to interact with Oracle.
> 
> I've been basing the code below on what I found in this thread
> http://www.thescripts.com/forum/thread33728.html .
> 
> Zach-
> 
> import cx_Oracle
> 
> connection = cx_Oracle.connect("user/[EMAIL PROTECTED]")
> 
> ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum
> varchar2, p_prefix number)
> 
> cur = connection.cursor()
> 
> repParams = {}
> repParams['arg1'] = "555"
> repParams['arg2'] = "2"
> repParams['arg3'] = "999"
> 
> sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3);
> end;"""
> 
> cur.execute(sqlStr, repParams)
> 
> connection.commit
> 
> cur.close
> 
> connection.close

You forgot to call the methods using the ()-operator.

connection.commit()

and so forth.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get an XML DOM while offline?

2008-03-19 Thread Diez B. Roggisch
william tanksley wrote:

> I want to parse my iTunes Library xml. All was well, until I unplugged
> and left for the train (where I get most of my personal projects
> done). All of a sudden, I discovered that apparently the presence of a
> DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
> the Internet... So suddenly I was unable to do any work.
> 
> I don't want to modify the iTunes XML; iTunes rewrites it too often.
> How can I prevent xml.dom.minidom from dying when it can't access the
> Internet?
> 
> Is there a simpler way to read the iTunes XML? (It's merely a plist,
> so the format is much simpler than general XML.)

Normally, this should be solved using an entity-handler that prevents the
remote fetching. I presume the underlying implementation of a SAX-parser
does use one, but you can't override that (at least I didn't find anything
in the docs)

The most pragmatic solution would be to rip the doctype out using simple
string methods and/or regexes.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Preston Landers
On Mar 19, 9:12 am, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
wrote:

> So - where should I propose these changes?  Here?  python-dev?  Should  
> I write up a full PEP or should I just give a more informal outline  
> with code samples?  

My guess is that the python-dev folks would send you here or to the
python-ideas mailing list.  My suggestion is to give a more informal
outline with code samples either here or in python-ideas before
proceeding any further.

Preston
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speaking Text

2008-03-19 Thread Grant Edwards
On 2008-03-19, David C  Ullrich <[EMAIL PROTECTED]> wrote:
> Mac OS X has text-to-speech built into the interface.
> So there must be a way to access that from the command
> line as well - in fact the first thing I tried worked:
>
> os.system('say hello')
>
> says 'hello'.
>
> Is there something similar in Windows and/or Linux?

The only speach sythesizer I've seen on Linux boxes is festival:

  http://www.cstr.ed.ac.uk/projects/festival/

You can use os.system() to run it from the "command line" or
there are various client APIs:

  http://www.cstr.ed.ac.uk/projects/festival/manual/festival_28.html#SEC126

But, it's not installed by default on any distros I've ever
used...

-- 
Grant

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cx_Oracle execute procedure

2008-03-19 Thread Jerry Hill
On Wed, Mar 19, 2008 at 11:03 AM, Poppy <[EMAIL PROTECTED]> wrote:
> I've been working on the code below and and executes silently, no
>  complaints, however the end result should be a record in my table and it's
>  not added. The procedure works with the passed credentials using SQLPlus or
>  SQL Developer clients. However I'm not sure if I'm constructing my python
>  code correctly to interact with Oracle.
...
>  connection.commit
>  cur.close
>  connection.close

You have to actually call these methods:
connection.commit()
cur.close()
connection.close()

Without the parentheses, you're just getting a reference to the
methods and immediately discarding them.

-- 
Jerry
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get an XML DOM while offline?

2008-03-19 Thread william tanksley
I want to parse my iTunes Library xml. All was well, until I unplugged
and left for the train (where I get most of my personal projects
done). All of a sudden, I discovered that apparently the presence of a
DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
the Internet... So suddenly I was unable to do any work.

I don't want to modify the iTunes XML; iTunes rewrites it too often.
How can I prevent xml.dom.minidom from dying when it can't access the
Internet?

Is there a simpler way to read the iTunes XML? (It's merely a plist,
so the format is much simpler than general XML.)

-Wm
-- 
http://mail.python.org/mailman/listinfo/python-list


cx_Oracle execute procedure

2008-03-19 Thread Poppy
I've been working on the code below and and executes silently, no 
complaints, however the end result should be a record in my table and it's 
not added. The procedure works with the passed credentials using SQLPlus or 
SQL Developer clients. However I'm not sure if I'm constructing my python 
code correctly to interact with Oracle.

I've been basing the code below on what I found in this thread 
http://www.thescripts.com/forum/thread33728.html .

Zach-

import cx_Oracle

connection = cx_Oracle.connect("user/[EMAIL PROTECTED]")

## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum 
varchar2, p_prefix number)

cur = connection.cursor()

repParams = {}
repParams['arg1'] = "555"
repParams['arg2'] = "2"
repParams['arg3'] = "999"

sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); 
end;"""

cur.execute(sqlStr, repParams)

connection.commit

cur.close

connection.close


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAP Server in Python

2008-03-19 Thread dave_mikesell
On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:

> I am basically looking to do the same thing in Python as easily.
>
> Any help or pointers would be appreciated.

Googling for "python soap" turned up a few hits that may help you.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving datetime

2008-03-19 Thread Mike Driscoll
On Mar 19, 9:12 am, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
wrote:
> This is a query for information as to how to proceed.  I am not a
> professional programmer, but I use Python a great deal to help me in
> my main job, which involves designing schedules for a global airline.
> As such, I use datetime (and dateutil) extensively, and after much
> use, I have come to some conclusions about their utility, and how to
> improve them.  Some of these changes are quite minor and would result
> in a large increase in utility (low hanging fruit), while some changes
> are major, and would result in less obvious benefits - but these
> changes would increase the 'Python Zen' of them.
>
> So - where should I propose these changes?  Here?  python-dev?  Should
> I write up a full PEP or should I just give a more informal outline
> with code samples?  I would volunteer to help maintain/improve
> datetime, but I don't speak C at all, unfortunately, and datetime
> appears to be in C.
>
> In addition, I have little contact with the Python community - I work
> somewhat 'solo' when it comes to my programming projects.  So, are
> there other people out there who use datetime?  Dateutil?  What do you
> find the deficits/benefits of these modules to be?
>
> Thank you for your thoughts
>
> Nick Fabry

I think you need to do this sort of thing on python-dev. I'm not sure
how the PEP process works though. If you give your thoughts in a PEP-
like format, you'd probably be taken more seriously though.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Improving datetime

2008-03-19 Thread Nicholas F. Fabry
This is a query for information as to how to proceed.  I am not a  
professional programmer, but I use Python a great deal to help me in  
my main job, which involves designing schedules for a global airline.   
As such, I use datetime (and dateutil) extensively, and after much  
use, I have come to some conclusions about their utility, and how to  
improve them.  Some of these changes are quite minor and would result  
in a large increase in utility (low hanging fruit), while some changes  
are major, and would result in less obvious benefits - but these  
changes would increase the 'Python Zen' of them.

So - where should I propose these changes?  Here?  python-dev?  Should  
I write up a full PEP or should I just give a more informal outline  
with code samples?  I would volunteer to help maintain/improve  
datetime, but I don't speak C at all, unfortunately, and datetime  
appears to be in C.

In addition, I have little contact with the Python community - I work  
somewhat 'solo' when it comes to my programming projects.  So, are  
there other people out there who use datetime?  Dateutil?  What do you  
find the deficits/benefits of these modules to be?

Thank you for your thoughts

Nick Fabry

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing names of items in a list

2008-03-19 Thread Simon Brunning
On Wed, Mar 19, 2008 at 2:21 PM, royG <[EMAIL PROTECTED]> wrote:
> hi
>  i am trying to rename extension of files in a directory..as an initial
>  step i made a method in
>
>  class ConvertFiles:
>  def __init__(self,infldr,outfldr):
>  self.infldr=infldr
>  self.outfldr=outfldr
>  self.origlist=os.listdir(infldr)
>  
>  def renamefiles(self,extn):
>  for x in self.origlist:
>  x=x+"."+extn
>
>  ...
>
>  later when i print self.origlist  i find that the elements of list are
>  unchanged..even tho  a print x  inside the renamefiles()  shows that
>  extn is appended to x  ..
>  why does this happen?

Your 'x=' line is building a brand new string, and rebinding the name
'x' to it. It's not doing anything to the original list. See
.

I'd rewrite that as (untested):

def renamefiles(self, extn):
self.origlist = list((x + "." + extn) for x in self.origlist)

or

def renamefiles(self, extn):
self.origlist = list(("%s.%s" % (z, extn)) for x in self.origlist)

Better still, take a look at the os.path module...

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing names of items in a list

2008-03-19 Thread Diez B. Roggisch
royG wrote:

> hi
> i am trying to rename extension of files in a directory..as an initial
> step i made a method in
> 
> class ConvertFiles:
>  def __init__(self,infldr,outfldr):
>  self.infldr=infldr
>  self.outfldr=outfldr
>  self.origlist=os.listdir(infldr)
> 
>  def renamefiles(self,extn):
>  for x in self.origlist:
>  x=x+"."+extn
> 
> ...
> 
> later when i print self.origlist  i find that the elements of list are
> unchanged..even tho  a print x  inside the renamefiles()  shows that
> extn is appended to x  ..
> why does this happen?

Because a piece of code like this

x = some_list[index]
x = something_else()

doesn't change the object itself, just rebinds x to a new object. That the
old object stored in x happened to be referenced in a list as well - who
cares?

So either your members of origlist become mutables - then you have to alter
them, and then they will be reachable from the list. Like this:

class Foo(object):
def __init__(self):
pass

l = [Foo() for _ in xrang(10)]

f = l[0]
f.bar = "baz"

print l[0].bar

Or you rebind the list itself, or it's index under work - like this:

for i, item in enumerate(l):
l[i] = do_something_with_item(item)

or

new_l = []
for item in l:
new_l.append(do_something(item))
l = new_l

There are innumerable variations of this scheme. 

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Generalizing PEP 370 (per user site-packages directory) via .pth files

2008-03-19 Thread ago
Dear all,

I was reading pep 370, "Per user site-packages directory"
http://www.python.org/dev/peps/pep-0370/, and was wondering if the
concept couldn't be generalized by having ways to pass a .pth file as
commandline argument and/or via an environment variable (PYTHONPATH
could also be used to feed .pth files) and/or via special named files
such as ~/.python2.6-user.pth or ./python2.6-local.pth, or possibly
even reusing the paths in the distutils configuration files (under
[install]).

Any path in the above files would be added to sys.path and scanned
recursively for other pth files.  The system would also load
default.pth from a pre-defined location (e.g. /etc/python2.6/
default.pth), which would point to the default site-packages
directory. There should also be a mechanism to disable/override
default.pth for situations where a clean environment is desired.

This would make it easier to setup special testing environments,
perform local installations, and allow for file-based deployments (in
simple scenarios), without resorting to special tools such as virtual-
python, editing site.py and/or requiring sysadmin intervention. It
would be particularly useful in environments where there is a clear
separation between IT and developer roles.

I just started giving some thoughts to the concept and I am not fully
aware of the implications and requirements of the proposal, but even
if the above turns out to be impractical, I hope that a debate on the
topic will be beneficial.

Ago
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >