Email Bounce Detection

2008-06-27 Thread madhav
Hello everybody, I need a mechanism to detect email bounces. I tried
browsing through smtplib implementation and found not helpful in this
case. Actually it is said in the documentation that if a mail is sent
to say: "[EMAIL PROTECTED]", then "_send()" in the
SMTPConnection class returns 550(Unknown recceipient). I checked the
same but its not returning 550 and return 250(receipient ok).
Later, I tried getting the smtp error code from the mail body of a
bounced msg. the "Message" class doesnot have any error code attribute
by default. We need to get it from the mailbody(by regex ing), which i
think is not a valid solution, as "550" can occur anywhere in the body
of any message otherthan the bounced msg also.
Please help me regarding this.
Thanks in advance.

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


Re: Question on time module

2008-06-27 Thread subhabrata . iisc
This problem is solved with time.gmtime

[EMAIL PROTECTED] wrote:
> Dear Members of the group,
> I have one function
> def sum1(n):
>   a1=5
>   a2=6
>   a3=a1+a2
>   a4=a3+8
>   print "The First sum is"
>   print a3
>   print "The Second sum is"
>   print a4
>
> Now, I want to do it in a way, a4 is calculated after a given time
> interval of a3 -this is easy but if I want to check after how much
> time a4 is calculated from a3 how can I do?
> If any one can help it.
> Best Regards,
> Subhabrata.
--
http://mail.python.org/mailman/listinfo/python-list


Re: the problem about the DLL file generate by py2exe

2008-06-27 Thread em00100
On Jun 26, 7:52 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Dear All,
>
> > I have try to use the py2exe to compile the DLL file
>
> > first i write the simple python script "test01.py":
> > def test001():
> >     return 1
>
> > then write the setup.py:
> > # setup.py
> > from distutils.core import setup
> > import py2exe
> > import sys
>
> > if len(sys.argv) == 1:
> >     sys.argv.append("py2exe")
> >     sys.argv.append("-q")
>
> > class Target:
> >     def __init__(self, **kw):
> >         self.__dict__.update(kw)
> >         # for the version info resources (Properties -- Version)
> >         self.version = "0.0.1"
> >         self.company_name = "Nil"
> >         self.copyright = "Nil"
> >         self.name = "test"
>
> > testTK = Target(
> >     # used for the versioninfo resource
> >     description = "test app",
> >     # what to build
> >     modules = ["test01"],
> >     script = "test01.py",
> >     # specify which type of com server you want (exe and/or dll)
> >     create_exe = False,
> >     create_dll = True)
>
> > #setup(windows=["hkcity_ide_main.py"])
> > setup(
> >     name='Test',
> >     options={"py2exe": {"bundle_files": 1, }},
> >     zipfile=None,
> >     version='1.0',
> >     description='Test',
> >     author='',
> >     author_email='',
> >     url='',
> >     ctypes_com_server=[testTK],
> >     )
>
> > and compile the it by the command:
>
> > C:\Python25\python setup.py py2exe
>
> > I use the script try to call the function "test001" in the "test01.py"
> > from ctypes import *
> > test01 = cdll.LoadLibrary("test01.dll")
> > test001 = test01.test001
> > print test01()
>
> > However, this is out the error:
> > AttributeError: function 'test001' not found
>
> > Is it any problem when i define the function?
>
> I guess you should define a python-function, inside which you call your
> dll-function.
>
> Diez

How to define the "python-function"?
can you write the statement with my testing script, please.
the "python-function" is place in "test01.py"?
is it also need to define the "python-function" in "setup.py"

thanks for you time
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help me on Backspace please

2008-06-27 Thread cakomo
On Jun 27, 3:06 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Jun 27, 6:32 am, [EMAIL PROTECTED] wrote:
>
> > Hi
> > I am a beginner on Python and have a problem..
>
> > I have text file and reading it line by line and there are backspace
> > characters in it like '\b' or anything you want like "#".  I want to
> > replace these chars. with Backspace action. I mean deleting the
> > previous char. and the \b char also. and writing all cleaned text to a
> > file again.
>
> > How can I do that.
>
> I haven't seen anything like that for ... ummm, a very long time. Used
> for bolding and making up your own characters on a daisy-wheel
> printer. Where did you get the file from?
>
> If there are no cases of multiple adjacent backspaces (e.g. "blahfoo\b
> \b\bblah") you can do:
>    new_line = re.sub(r'.\x08', old_line, '')
>
> Note: using \x08 for backspace instead of \b to avoid having to worry
> about how many \ to use in the regex :-)
>
> Otherwise you would need to do something like
>    while True:
>       new_line = re.sub(r'[^\x08]\x08', '', old_line)
>       if new_line == old_line: break
>       old_line = new_line
>
> And if you were paranoid, you might test for any remaining stray
> backspaces, just in case the line contains "illegal" things like
> "\bfoo" or "foo\b\b\b\b" etc.
>
> Cheers,
> John

Thanks John
I will try it but, do you think regex replacement gonna erase the
prev. char.?

Thanks  a lot for your reply.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Email Bounce Detection

2008-06-27 Thread Maric Michaud
Le Friday 27 June 2008 09:03:15 madhav, vous avez écrit :
> Hello everybody, I need a mechanism to detect email bounces. I tried
> browsing through smtplib implementation and found not helpful in this
> case. Actually it is said in the documentation that if a mail is sent
> to say: "[EMAIL PROTECTED]", then "_send()" in the
> SMTPConnection class returns 550(Unknown recceipient). I checked the
> same but its not returning 550 and return 250(receipient ok).

This is not the same scenario, the SMTP server that will respond 550 is the MX 
for the domain, if you send your mails using an outgoing SMTP server, it 
can't know in advance the list of remote adressesbut will bounce your message 
when receiving the 550 from the remote MX.

> Later, I tried getting the smtp error code from the mail body of a
> bounced msg. the "Message" class doesnot have any error code attribute
> by default. We need to get it from the mailbody(by regex ing), which i
> think is not a valid solution, as "550" can occur anywhere in the body
> of any message otherthan the bounced msg also.
> Please help me regarding this.
> Thanks in advance.

Bounces are multipart messages easily parsed with the email package of the 
stdlib (dont' use regexes here).

Abounce message is of type :

Content-Type: multipart/report;
  report-type=delivery-status;  

a delivery-status imply that one of the subpart of the message is a 
message/delivery-status with all needed infos set in the headers. This one is 
taken from a real example :

Content-Description: Delivery report
Content-Type: message/delivery-status

Reporting-MTA: dns; aristote.info
X-Postfix-Queue-ID: 1D07D1409FF
X-Postfix-Sender: rfc822; [EMAIL PROTECTED]
Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST)

Final-Recipient: rfc822; [EMAIL PROTECTED]
Original-Recipient: rfc822;[EMAIL PROTECTED]
Action: failed
Status: 5.0.0
Remote-MTA: dns; tyrande.nerim.net
Diagnostic-Code: smtp; 550 <[EMAIL PROTECTED]>: Recipient address 
rejected:
User unknown in local recipient table


So, for example :


>>>[48]: import email

>>>[49]: bounce = email.message_from_string(open('ex.eml').read())

>>>[50]: bounce.get_content_type()
...[50]: 'multipart/report'

>>>[51]:

>>>[52]: for i in bounce.get_payload() :
   :if i.get_content_type() == 'message/delivery-status' :
   : print i.get_payload()[1]['status']
   :
   :
5.0.0




-- 
_

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


Re: extend getattr()

2008-06-27 Thread Jared Grubb
You could overload __getattr__ (might have to play around a bit to make sure
any possible AttributeError's look right, but the basic idea is here)
class A(object):
  # ...
  def __getattr__(self, name):
  try:
return object.__getattribute__(self, name)
  except AttributeError:
if '.' in name:
  attrs = name.split('.')
  first = object.__getattribute__(self, attrs[0])
  return getattr(first, '.'.join(attrs[1:]))
raise

>>> a = A()
>>> a.b = A()
>>> a.b.c = A()
>>> a.b.c.d = A()
>>> getattr(a, 'b.c.d')
<__main__.A object at 0x67f50>




On 26 Jun 2008, at 04:06, Rotlaus wrote:

Hello,

lets assume i have some classes:

class A(object):
   def __init__(self):
   b = B()

class B(object):
   def __init__(self):
   c = C()

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

and now i wanna do something like this:

a=A()
c=getattr(a, 'b.c')

I know this doesn't work, but what can i do to get this or a similar
functionality to get it work for this sample and for even more nested
classes?

Kind regards,

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

Earn 25 US$ in just 5 mins . . .

2008-06-27 Thread swetav02
Earn 25 US$ in just 5 mins . . .

You can earn 25 US$ in just 5mins from now, please follow the simple
steps:
It's absolutely free to join.

Step 01
CLICK HERE
http://www.awsurveys.com/HomeMain.cfm?RefID=242423
A page will open

Step 02
Click on "Create a Free Account"

Step 03
Fill up the details and register.

Step 04
After registration, go to home. You will see - The Following Surveys
are Available:
A list of surveys is given under this heading. Just click on those
surveys and fill up the details. You will get paid.

For More Details Plz contact me : [EMAIL PROTECTED]

Click Here For More Earning opportunities
http://freemoneyteamonline.blogspot.com/
CLICK HERE TO VISIT MY WEBSITE
http://www.sweta-verma.blogspot.com/
Regards
Sweta Verma
--
http://mail.python.org/mailman/listinfo/python-list


Question on List

2008-06-27 Thread subhabrata . iisc
Dear All,
I am trying to write the following code:

def try1(n):
a1="God Godess Borother Sister Family"
a2=a1.split()
a3=raw_input("PRINT A WORD")
a4=a1.find(a3)
print a4
a5=[]
if a4>0:
a5=a2.index(a3)
a6=a5+1
a7=a2[a6]
print "The new word is"
print a7
a8=a5.append(a7)
print a5
elif a4<0:
a11=a3
print "The word is not availiable in String"
print a11
a6=a5.append(a11)
print a5
else:
print "Error"

Now, my question is I like to see a5 or the empty list as appended
with elements. Results I am getting is a5 giving single value like
['God'],['Godess']... but I like to see it as ['God','Godess'...] etc.
Am I going wrong?
Do I have to rethink it in some other way?
If any one can kindly let me know.
Best Regards,
Subhabrata.
--
http://mail.python.org/mailman/listinfo/python-list


Re: list previous or following list elements

2008-06-27 Thread Bruno Desthuilliers

antar2 a écrit :

Hello


Suppose I have a textfile (text1.txt) with following four words:

Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:


def next_if(predicate, iterable):
if not hasattr(iterable, next):
iterable = iter(iterable)
for element in iterable:
if predicate(element):
yield iterable.next()


f = open('/home/bruno/text1.txt', 'r')
for elt in next_if(lambda x: x.startswith('b'), f):
print elt.strip()
f.close()



I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

import re
f = open('text1.txt', 'r')
list1 = []
list2 = []
for line in f:
list1.append(line)
a = re.compile("^b")
int = 0
while(int <= list1[-1]):
int = int + 1
a_match = a.search(list1[int])
if(a_match):
list2.append(list1[int + 1])
print list2


f = open('text1.txt')
lines = f.readlines()
f.close()
matchings = [
   next for line, next in zip(lines, lines[1:])
   if line.startswith('b')
   ]

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


Re: Help me on Backspace please

2008-06-27 Thread John Machin
On Jun 27, 5:27 pm, cakomo <[EMAIL PROTECTED]> wrote:
> On Jun 27, 3:06 am, John Machin <[EMAIL PROTECTED]> wrote:
> >    new_line = re.sub(r'.\x08', old_line, '')
>
> >       new_line = re.sub(r'[^\x08]\x08', '', old_line)
>
> Thanks John
> I will try it but, do you think regex replacement gonna erase the
> prev. char.?

Yair i think its gunna y do u ask?
--
http://mail.python.org/mailman/listinfo/python-list


Re: recursion in Class-methods?

2008-06-27 Thread Bruno Desthuilliers

defn noob a écrit :

class Graph(object):

where does anyone write like that?


Almost everywhere nowadays.


I've seen only examples like i have
written.


Most of the doc has still not been updated since the introduction of 
newstyle classes years ago. You'll find more here:

http://docs.python.org/ref/node33.html



is the object then passed to init?


Nope, it's the base class for your Graph class.



class Graph(object):
def __init__(self, dictionary):
self.structure = dictionary

or

class Graph(object):
def __init__(self, object):
self.structure = object



parent class list in a class statement and argument list of an 
initializer are totally unrelated.


The syntax for a class statement is:
classdef::= "class" classname [inheritance] ":" suite
inheritance ::= "(" [expression_list] ")"
classname   ::= identifier

cf http://docs.python.org/ref/class.html



and "mutable containers", do you refer to "path=[]" as a parameter.


Indeed. This is one of the most (in)famous Python gotchas.
--
http://mail.python.org/mailman/listinfo/python-list


Re: list previous or following list elements

2008-06-27 Thread Bruno Desthuilliers

Terry Reedy a écrit :
(snip)

I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python.  


Or simply:
wordlist = open('words.txt').readlines()


In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
if word[0] == 'b':


While this is perfectly legal, I'd rather use word.startswith('b') here. 
But don't ask me why !-)


print(wordlist[i+1]) 


Hmmm... Guess what will happen if wordlist == ['Apple', 'balcony'] ?



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


Re: Email Bounce Detection

2008-06-27 Thread madhav
On Jun 27, 12:34 pm, Maric Michaud <[EMAIL PROTECTED]> wrote:
> Le Friday 27 June 2008 09:03:15 madhav, vous avez écrit :
>
> > Hello everybody, I need a mechanism to detect email bounces. I tried
> > browsing through smtplib implementation and found not helpful in this
> > case. Actually it is said in the documentation that if a mail is sent
> > to say: "[EMAIL PROTECTED]", then "_send()" in the
> > SMTPConnection class returns 550(Unknown recceipient). I checked the
> > same but its not returning 550 and return 250(receipient ok).
>
> This is not the same scenario, the SMTP server that will respond 550 is the MX
> for the domain, if you send your mails using an outgoing SMTP server, it
> can't know in advance the list of remote adressesbut will bounce your message
> when receiving the 550 from the remote MX.
>
> > Later, I tried getting the smtp error code from the mail body of a
> > bounced msg. the "Message" class doesnot have any error code attribute
> > by default. We need to get it from the mailbody(by regex ing), which i
> > think is not a valid solution, as "550" can occur anywhere in the body
> > of any message otherthan the bounced msg also.
> > Please help me regarding this.
> > Thanks in advance.
>
> Bounces are multipart messages easily parsed with the email package of the
> stdlib (dont' use regexes here).
>
> Abounce message is of type :
>
> Content-Type: multipart/report;
>   report-type=delivery-status;  
>
> a delivery-status imply that one of the subpart of the message is a
> message/delivery-status with all needed infos set in the headers. This one is
> taken from a real example :
>
> Content-Description: Delivery report
> Content-Type: message/delivery-status
>
> Reporting-MTA: dns; aristote.info
> X-Postfix-Queue-ID: 1D07D1409FF
> X-Postfix-Sender: rfc822; [EMAIL PROTECTED]
> Arrival-Date: Fri, 27 Jun 2008 09:10:14 +0200 (CEST)
>
> Final-Recipient: rfc822; [EMAIL PROTECTED]
> Original-Recipient: rfc822;[EMAIL PROTECTED]
> Action: failed
> Status: 5.0.0
> Remote-MTA: dns; tyrande.nerim.net
> Diagnostic-Code: smtp; 550 <[EMAIL PROTECTED]>: Recipient address
> rejected:
>     User unknown in local recipient table
>
> So, for example :
>
> >>>[48]: import email
> >>>[49]: bounce = email.message_from_string(open('ex.eml').read())
> >>>[50]: bounce.get_content_type()
>
> ...[50]: 'multipart/report'
>
> >>>[51]:
> >>>[52]: for i in bounce.get_payload() :
>
>    :    if i.get_content_type() == 'message/delivery-status' :
>    :         print i.get_payload()[1]['status']
>    :
>    :
> 5.0.0
>
> --
> _
>
> Maric Michaud

Thankyou somuch Maric. Will try the approach you have mentioned. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding functions to an existing instance

2008-06-27 Thread Bruno Desthuilliers

Allen a écrit :

[EMAIL PROTECTED] wrote:

On 26 juin, 17:18, Allen <[EMAIL PROTECTED]> wrote:

I need a way to add a method to an existing instance, but be as close as
possible to normal instance methods.


def set_method(obj, func, name=None):
  if not name:
name = func.__name__
  setattr(obj, name, func.__get__(obj, type(obj)))

class Toto(object):
  pass

toto = Toto()

def titi(self):
  print self

set_method(toto, titi)



I tried that.  func.__get__(obj, type(obj)) creates a bound method 


Indeed, since this is how bound methods are created anyway.

and 
then sets an attribute to that, creating a cyclic reference.  toto 
contains a reference to the bound method, the bound method contains a 
reference to the instance toto.


Yes, true. I suppose you have good reasons to worry about cyclic 
references here, but I fail to imagine what they are.


Another solution might be to create new class on the fly from the 
instance's class, inserting the function in the attribs dict, and then 
rebind the instance's __class__ to this new class, but that might be a 
bit overkill.



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


Work 2 Hrs at Net EARN 10,000/- Rs Above

2008-06-27 Thread lovely
HAI..
Guys this web site s very useful to
you...
How This site
helps..
how to earn money form
online..
In this site, you wil earn more than 1/- Rs per month
its true ... just login this site and  << EARN MONEY
>>

www.freeonlinedollers.blogspot.com

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


Work 2 Hrs at Net EARN 10,000/- Rs Above

2008-06-27 Thread lovely
HAI..
Guys this web site s very useful to
you...
How This site
helps..
how to earn money form
online..
In this site, you wil earn more than 1/- Rs per month
its true ... just login this site and  << EARN MONEY
>>

www.freeonlinedollers.blogspot.com

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


using urllib2

2008-06-27 Thread Alexnb

I have never used the urllib or the urllib2. I really have looked online for
help on this issue, and mailing lists, but I can't figure out my problem
because people haven't been helping me, which is why I am here! :]. Okay, so
basically I want to be able to submit a word to dictionary.com and then get
the definitions. However, to start off learning urllib2, I just want to do a
simple google search. Before you get mad, what I have found on urllib2
hasn't helped me. Anyway, How would you go about doing this. No, I did not
post the html, but I mean if you want, right click on your browser and hit
view source of the google homepage. Basically what I want to know is how to
submit the values(the search term) and then search for that value. Heres
what I know:

import urllib2
response = urllib2.urlopen("http://www.google.com/";)
html = response.read()
print html

Now I know that all this does is print the source, but thats about all I
know. I know it may be a lot to ask to have someone show/help me, but I
really would appreciate it. 
-- 
View this message in context: 
http://www.nabble.com/using-urllib2-tp18150669p18150669.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: sqlite3 alternative option

2008-06-27 Thread Uwe Grauer

Gandalf wrote:

Hi every one I'm looking for a good alternative db to replace sqlite

I'm using pySQlite3, And I tried to translate very big database from
Mysql to sqlite.
I generated through  PHP a python script that insert 200,000 records
to my sqlite db and took me more then 5 hours and managed to insert
only  100,000 records.
I have almost million records so I need a better solution.


thank you


Use Firebird. It has a small footprint and runs in different
enviroments from embedded to server with single process per connection.

http://www.firebirdsql.org
http://www.firebirdfaq.org

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


Re: Help me on Backspace please

2008-06-27 Thread cakomo
On Jun 27, 11:09 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Jun 27, 5:27 pm, cakomo <[EMAIL PROTECTED]> wrote:
>
> > On Jun 27, 3:06 am, John Machin <[EMAIL PROTECTED]> wrote:
> > >    new_line = re.sub(r'.\x08', old_line, '')
>
> > >       new_line = re.sub(r'[^\x08]\x08', '', old_line)
>
> > Thanks John
> > I will try it but, do you think regex replacement gonna erase the
> > prev. char.?
>
> Yair i think its gunna y do u ask?

Sorry John

Did i said i am a newbie still trying to figure out. But regex
statement is really  what i want. Thank you very much :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 alternative option

2008-06-27 Thread Gerhard Häring

Uwe Grauer wrote:

Gandalf wrote:

Hi every one I'm looking for a good alternative db to replace sqlite

I'm using pySQlite3, And I tried to translate very big database from
Mysql to sqlite.
I generated through  PHP a python script that insert 200,000 records
to my sqlite db and took me more then 5 hours and managed to insert
only  100,000 records.
I have almost million records so I need a better solution.



Use Firebird. It has a small footprint and runs in different
enviroments from embedded to server with single process per connection.


Firebird may be nice, but has nothing to do with this performance problem.

You'll have to make quite an effort to get such abysmal performance with 
pysqlite. Like explictly turning autocommit mode on.


On this 5 year old box and with a simplistic table, it takes 20 seconds 
to insert 200k records with index, 13 seconds without index, and 18 
seconds with creating the index after the bulk insert.


With turning autocommit mode on, inserting only 2000 records already 
takes 22 seconds!


For some reason, it's a typical newbie thing to turn autocommit on, or 
recommend doing so to others ...


-- Gerhard

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


how can I specify a timeout value to Semaphore.acquire()?

2008-06-27 Thread Bruza
Not sure if this is related. But I found a "patch" to Python 2.4 to
support adding "timeout" parameter to Semaphore.acquire() (http://
mail.python.org/pipermail/patches/2003-November/013796.html).

However, when I try the "timeout" parameter on Python 2.5.1 running on
Ubuntu 7.10 and I got an error of:

 acquire() got an unexpected keyword argument 'timeout'

Is there a way to specify a timeout value to Semaphore.acquire(), or I
have to implement my own "SuperSemaphore"?

Thanks in advance,

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


Re: where is the error?

2008-06-27 Thread lajam
Maybe I didn't explain correctly what i wanted to do. I have a
database and I just want to pick data under a certain criteria. So I
wanted to use a function like nonzero or find or where to find the
line for corresponding to the data following this criteria. So to find
the lines, I used nonzero and it corresponds to the command:

diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()

so YES it has SOMETHING to do with the question below.

diff_temp=(array([  0,   6,   7,  10,  14,  15,  16,  17,  21,  22,
24,  25,  26,
27,  31,  32,  33,  36,  37,  38,  39,  40,  41,  42,  46,
47,
48,  49,  50,  51,  52,  53,  54,  59,  60,  61,  62,  71,
72,
73,  74,  75,  80,  81,  82,  83,  84,  85,  86,  87,  88,
89,
90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101,
102,
   103, 104, 105, 106, 107, 111, 112, 113, 114, 115, 116]),)

So now I just want to have the data corresponding to those lines.
Thinking that python was a powerful tool, I thought that it was just
possible to assign those line directly in a matrix. So I used the
command:

values_matchup=values_Stumpf[diff_temp_Stumpf,:]

But it didn't work. I'm sure that there is a specific reason. But my
concern was that this command works FINE if I use python on windows xp
but doesn't work if I use python on my linux Ubuntu machine. So I
wondered what was wrong and if there is a easy and simple way to get
directly a new array with the data corresponding to a certain
criteria.

Thanks for the help,
Cedric












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


Re: Question on List

2008-06-27 Thread Chris
On Jun 27, 9:51 am, [EMAIL PROTECTED] wrote:
> Dear All,
> I am trying to write the following code:
>
> def try1(n):
>         a1="God Godess Borother Sister Family"
>         a2=a1.split()
>         a3=raw_input("PRINT A WORD")
>         a4=a1.find(a3)
>         print a4
>         a5=[]
>         if a4>0:
>                 a5=a2.index(a3)
>                 a6=a5+1
>                 a7=a2[a6]
>                 print "The new word is"
>                 print a7
>                 a8=a5.append(a7)
>                 print a5
>         elif a4<0:
>                 a11=a3
>                 print "The word is not availiable in String"
>                 print a11
>                 a6=a5.append(a11)
>                 print a5
>         else:
>                 print "Error"
>
> Now, my question is I like to see a5 or the empty list as appended
> with elements. Results I am getting is a5 giving single value like
> ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc.
> Am I going wrong?
> Do I have to rethink it in some other way?
> If any one can kindly let me know.
> Best Regards,
> Subhabrata.

First notes, the string .find() method return -1 for not found and
zero or above if the search string is present.  Remember you count
from zero.  Secondly, list .append() methods do not return a new list
but modify the list in place.  Thirdly, the .index() method of a list
requires an integer and not a string.  And lastly, indentation should
be 4 spaces not 8.

Just doing a sloppy job on the code (and my interpretation of what you
wanted)

def try1(n):
new_list = []
input_string="God Godess Borother Sister Family"
while n:
user_selection=raw_input("PRINT A WORD")
if input_string.find(user_selection) > -1:
s = input_string.split()
i = [i for i,j in enumerate(s) if j == user_selection]
new_word = s[i+1]
print 'The new word is %s' % new_word
new_list.append(new_word)
print new_list
else:
print 'User selection of "%s" not in the string.' %
user_selection
new_list.append(user_selection)
print new_list
n -= 1

Obviously I'm going to assume that the code you posted excluded your
loop control for the "try n amount of times".  What was most likely
the cause is that you loop through your structure for every attempt of
the n times but each time you reset your list when you re-create it.

Hope that helps some.
Chris
--
http://mail.python.org/mailman/listinfo/python-list


Re: using urllib2

2008-06-27 Thread Maric Michaud
Le Friday 27 June 2008 10:43:06 Alexnb, vous avez écrit :
> I have never used the urllib or the urllib2. I really have looked online
> for help on this issue, and mailing lists, but I can't figure out my
> problem because people haven't been helping me, which is why I am here! :].
> Okay, so basically I want to be able to submit a word to dictionary.com and
> then get the definitions. However, to start off learning urllib2, I just
> want to do a simple google search. Before you get mad, what I have found on
> urllib2 hasn't helped me. Anyway, How would you go about doing this. No, I
> did not post the html, but I mean if you want, right click on your browser
> and hit view source of the google homepage. Basically what I want to know
> is how to submit the values(the search term) and then search for that
> value. Heres what I know:
>
> import urllib2
> response = urllib2.urlopen("http://www.google.com/";)
> html = response.read()
> print html
>
> Now I know that all this does is print the source, but thats about all I
> know. I know it may be a lot to ask to have someone show/help me, but I
> really would appreciate it.

This example is for google, of course using pygoogle is easier in this case, 
but this is a valid example for the general case :

>>>[207]: import urllib, urllib2

You need to trick the server with an imaginary User-Agent.

>>>[208]: def google_search(terms) :
return urllib2.urlopen(urllib2.Request("http://www.google.com/search?"; +  
urllib.urlencode({'hl':'fr', 'q':terms}),
   headers={'User-Agent':'MyNav 1.0 
(compatible; MSIE 6.0; Linux'})
  ).read()
   .:

>>>[212]: res = google_search("python & co")

Now you got the whole html response, you'll have to parse it to recover datas, 
a quick & dirty try on google response page :

>>>[213]: import re

>>>[214]: [ re.sub('<.+?>', '', e) for e in re.findall('.*?', 
res) ]
...[229]:
['Python Gallery',
 'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...',
 'Re: os x, panther, python & co: msg#00041',
 'Re: os x, panther, python & co: msg#00040',
 'Cardiff Web Site Design, Professional web site design services ...',
 'Python Properties',
 'Frees < Programs < Python < Bin-Co',
 'Torb: an interface between Tcl and CORBA',
 'Royal Python Morphs',
 'Python & Co']


-- 
_

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


Re: Getting column names from a cursor using ODBC module?

2008-06-27 Thread M.-A. Lemburg
John Machin wrote:
> On Jun 21, 11:58 pm, [EMAIL PROTECTED] wrote:
>> Is there any way to retrieve column names from a cursor using the ODBC
>> module? Or must I, in advance, create a dictionary of column position
>> and column names for a particular table before I can access column
>> values by column names? I'd prefer sticking with the ODBC module for
>> now because it comes standard in Python.
>>
>> I'm using Python 2.4 at the moment.
>>
> 
> Do you mean the odbc module? If so, it doesn't come standard in
> Python; it's part of the win32 package.
> 
> I haven't used it for years -- my preference on Windows these days
> would be mxODBC if the client would pay the licence fee, otherwise
> pyodbc. Sorry I'm not answering your question ... perhaps you should
> be asking a different question :)

mxODBC comes with a cursor.columns() method which allows you to
query column names and many other column specific details of the
database.

See the documentation for details:

http://www.egenix.com/products/python/mxODBC/#Documentation

If you just want to access the result set columns by name,
you can use the cursor.description tuple to map names to
positions.

Please also see the FAQ of the DB API spec reagrding the issues
involved with this approach:

http://www.python.org/dev/peps/pep-0249/

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2008-07-07: EuroPython 2008, Vilnius, Lithuania

 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiprecision arithmetic library question.

2008-06-27 Thread M.-A. Lemburg
duncan smith wrote:
> Michael Press wrote:
>> In article <[EMAIL PROTECTED]>,
>>  Mark Wooding <[EMAIL PROTECTED]> wrote:
>>
>>> Michael Press <[EMAIL PROTECTED]> wrote:
>>>
 I already compiled and installed the GNU multiprecision library
 on Mac OS X, and link to it in C programs. How do I link to the
 library from Python? 
>>> You know that Python already supports multiprecision integer arithmetic,
>>> right?  If you desperately want GMP, though, there's the gmpy module
>>> (q.g.).
>>
>> No, I do not know that. Define desperate. Does Python support the
>> extended Euclidean algorithm
>> and other number theory functions?
>> How fast does Python multiply?
>> Not that the latter is particularly important,
>> as C is built for speed.
>>
>> I've been fooling around. Ran dir(gmpy), and it does not show the full
>> complement of GMP
>> library functions, such as the various division
>> functions. e.g. mpz_tdiv_qr.
>>
> 
> There's also
> http://www.egenix.com/products/python/mxExperimental/mxNumber/.  I'm not
> sure how the functionality compares to GMPY.

mxNumber is a implementation of number types that use GMP for the
internals. It doesn't expose all APIs available in GMP and also doesn't
use a 1-1 mapping. Instead, it wraps the basic types available in GMP
in Python objects which can be used just like normal Python numbers.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2008-07-07: EuroPython 2008, Vilnius, Lithuania

 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


How do I unit-test a specific case of a home-rolled exception ?

2008-06-27 Thread Ken Starks

"""
I'm a bit new to both home-made exceptions and unit
tests, so sorry if I'm just being stupid or doing it
totally wrong.

I have an exception class, and I want to check that
a particular instance of it has been raised; or
more accurately that one is raised that is equal to
an instance I specify.

In the example below, I can check that a
'LongRationalError' is raised, but I want
to check that it is specifically a
'LongrationalError('1') or a 'LongRationalError('2')

How do I do that?

+

The critical line is:

self.assertRaises(LongRationalError, LongRational,  1, "7")

and it doesn't work if i put:


self.assertRaises(LongRationalError('2'), LongRational,  1, "7")


+++

"""

import unittest

class LongRationalError(Exception):
Message={}
Message['1']="numerator must be an integer"
Message['2']="denominator must be an integer"
def __init__(self, code):
self.code = str(code)
def __str__(self):
k = self.code
if k in self.Message.keys():
v = self.Message[k]
else:
v = '...no description provided'
return "Long Rational error #%s: %s" % (k,v)


class LongRational():
import types
allowed = [types.IntType,types.LongType]

def __init__(self,a,b):
if type(a) not in self.allowed:
raise LongRationalError("1")
if type(b) not in self.allowed:
raise LongRationalError("2")
if b == 0:
raise ValueError("supplied denominator must be non-zero")
if a == 0:
b = 1
self.numerator=long(a)
self.denominator=long(b)


class TestLongRationals(unittest.TestCase):


def test_init(self):
# if the supplied denominator ==  zero, we should get a ValueError
# if the supplied numerator or denominator is anything but an 
integer or a

# long we should
# raise a LongRational exception
from types import LongType
e = LongRational(123,456)
self.assertRaises(ValueError, LongRational,  1, 0)
self.assertRaises(LongRationalError, LongRational,  1.0, 2)
self.assertRaises(LongRationalError, LongRational,  3, 4.0)
self.assertRaises(LongRationalError, LongRational,  1, "7")
self.assertEquals(e.numerator,123)
self.assertEquals(e.denominator,456L)
self.assertEquals(type(e.numerator),LongType)
self.assertEquals(type(e.denominator),LongType)
# special case: denominator of zero rational forced to unity.
self.assertEquals(LongRational(0,24).denominator, 1L)



if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestLongRationals)
unittest.TextTestRunner(verbosity=2).run(suite)



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


Re: Cyclic imports

2008-06-27 Thread Carl Banks
On Jun 27, 12:58 am, James <[EMAIL PROTECTED]> wrote:
> > # a.py
> > import b
> > # refer to b.b
>
> > # b.py
> > import a
> > # refer to a.a
>
> Thanks Dan, but that still doesn't work for me I'm afraid...
>
> I renamed the modules avoid name overloading -- a.py is now:
> import b
>
> class A():
> print('b.b_mod:', b.b_mod)
>
> b is now defined, but b.b_mod isn't:
>   File "main.py", line 1, in 
> from a import a_mod
>   File "/Users/james/tmp/python/a/a_mod.py", line 3, in 
> class A():
>   File "/Users/james/tmp/python/a/a_mod.py", line 4, in A
> print('b.b_mod:', b.b_mod)
> AttributeError: 'module' object has no attribute 'b_mod'
>
> I must be missing something here - I've tried adding the modules to
> __all__ in __init__.py but that didn't help either.


The above print statement runs at module import time, so you're seeing
something that might not be an issue in functioning code.

For instance, if you rewrite A like the following:

class A(object):
def print_b(self):
print('b.b_mod:', b.b_mod)

If you call the print_b method from outside the module (say, from
main.py), it should work.


What lessons did we learn here?

Be aware of the difference between code that runs at module import
time, and code that runs after the module is imported.

In code that runs after the module has been imported (basically
anything defined in a function that isn't called by code that runs at
module time), you can expect the variables defined in the imported
module to be available.

In code that runs at module import time, there is no such guarantee,
so you have to arrange your modules so that code that depends on
another module is run after the dependent module.  (One common time
where this happens is when subclassing a class from another module:
the module with the base class needs to run first.)

If you have circular imports involved, making sure the modules import
in a certain order can be quite hairy.  (Faced with this problem, I
found it necessary to write an import hook to pre-import certain
modules.)


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


Re: where is the error?

2008-06-27 Thread John Machin
On Jun 27, 7:54 pm, [EMAIL PROTECTED] wrote:
> Maybe I didn't explain correctly what i wanted to do. I have a
> database and I just want to pick data under a certain criteria. So I
> wanted to use a function like nonzero or find or where to find the
> line for corresponding to the data following this criteria. So to find
> the lines, I used nonzero and it corresponds to the command:
>
> diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()
>
> so YES it has SOMETHING to do with the question below.
>
> diff_temp=(array([  0,   6,   7,  10,  14,  15,  16,  17,  21,  22,
> 24,  25,  26,
> 27,  31,  32,  33,  36,  37,  38,  39,  40,  41,  42,  46,
> 47,
> 48,  49,  50,  51,  52,  53,  54,  59,  60,  61,  62,  71,
> 72,
> 73,  74,  75,  80,  81,  82,  83,  84,  85,  86,  87,  88,
> 89,
> 90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101,
> 102,
>103, 104, 105, 106, 107, 111, 112, 113, 114, 115, 116]),)
>
> So now I just want to have the data corresponding to those lines.
> Thinking that python was a powerful tool, I thought that it was just
> possible to assign those line directly in a matrix. So I used the
> command:

You will need to explain what you mean by "assign those line directly
in a matrix". We are not mind-readers, and neither is Python.

>
> values_matchup=values_Stumpf[diff_temp_Stumpf,:]
>
> But it didn't work. I'm sure that there is a specific reason.

The specific reason is as Gary explained. What you have done is assign
the name diff_temp to some expression. This has absolutely nothing to
do with diff_temp_Stumpf which is an utterly different name, and as
far as we can tell has no referent as all, hence the error message
that you got.

You may need one of the following solutions:
(1)
diff_temp_Stumpf = diff_temp
(2)
def make_diff_temp_thing(values):
return (logical_and(v[:,5] > -2,v[:,5] < 2)).nonzero()
# much later ...
values_matchup = make_temp_thing(values_Stumpf)
but it's rather hard to understand what you want ...

> But my
> concern was that this command works FINE if I use python on windows xp
> but doesn't work if I use python on my linux Ubuntu machine.

The usual cause of this kind of phenomenon is experimental error e.g.
you didn't execute exactly the same statements (not "commands") on
Windows as on Linux.

> So I
> wondered what was wrong and if there is a easy and simple way to get
> directly a new array with the data corresponding to a certain
> criteria.

It might help if you use less abstract phrases than "corresponding to
a certain criteria". Can you relate how you would solve this problem
in a computer language other that Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on List

2008-06-27 Thread subhabrata . iisc
Hi Chris,
I solved the problem some other way round but thanx for your
suggestion, I'll review it also.
Best Regards,
Subhabrata.

Chris wrote:
> On Jun 27, 9:51�am, [EMAIL PROTECTED] wrote:
> > Dear All,
> > I am trying to write the following code:
> >
> > def try1(n):
> > � � � � a1="God Godess Borother Sister Family"
> > � � � � a2=a1.split()
> > � � � � a3=raw_input("PRINT A WORD")
> > � � � � a4=a1.find(a3)
> > � � � � print a4
> > � � � � a5=[]
> > � � � � if a4>0:
> > � � � � � � � � a5=a2.index(a3)
> > � � � � � � � � a6=a5+1
> > � � � � � � � � a7=a2[a6]
> > � � � � � � � � print "The new word is"
> > � � � � � � � � print a7
> > � � � � � � � � a8=a5.append(a7)
> > � � � � � � � � print a5
> > � � � � elif a4<0:
> > � � � � � � � � a11=a3
> > � � � � � � � � print "The word is not availiable in String"
> > � � � � � � � � print a11
> > � � � � � � � � a6=a5.append(a11)
> > � � � � � � � � print a5
> > � � � � else:
> > � � � � � � � � print "Error"
> >
> > Now, my question is I like to see a5 or the empty list as appended
> > with elements. Results I am getting is a5 giving single value like
> > ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc.
> > Am I going wrong?
> > Do I have to rethink it in some other way?
> > If any one can kindly let me know.
> > Best Regards,
> > Subhabrata.
>
> First notes, the string .find() method return -1 for not found and
> zero or above if the search string is present.  Remember you count
> from zero.  Secondly, list .append() methods do not return a new list
> but modify the list in place.  Thirdly, the .index() method of a list
> requires an integer and not a string.  And lastly, indentation should
> be 4 spaces not 8.
>
> Just doing a sloppy job on the code (and my interpretation of what you
> wanted)
>
> def try1(n):
> new_list = []
> input_string="God Godess Borother Sister Family"
> while n:
> user_selection=raw_input("PRINT A WORD")
> if input_string.find(user_selection) > -1:
> s = input_string.split()
> i = [i for i,j in enumerate(s) if j == user_selection]
> new_word = s[i+1]
> print 'The new word is %s' % new_word
> new_list.append(new_word)
> print new_list
> else:
> print 'User selection of "%s" not in the string.' %
> user_selection
> new_list.append(user_selection)
> print new_list
> n -= 1
>
> Obviously I'm going to assume that the code you posted excluded your
> loop control for the "try n amount of times".  What was most likely
> the cause is that you loop through your structure for every attempt of
> the n times but each time you reset your list when you re-create it.
>
> Hope that helps some.
> Chris
--
http://mail.python.org/mailman/listinfo/python-list

Re: sqlite3 alternative option

2008-06-27 Thread Uwe Grauer

Gerhard Häring wrote:

Uwe Grauer wrote:

Use Firebird. It has a small footprint and runs in different
enviroments from embedded to server with single process per connection.


Firebird may be nice, but has nothing to do with this performance problem.


I suggested Firebird because the OP asked:
> Hi every one I'm looking for a good alternative db to replace sqlite

Uwe

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


Re: How do I unit-test a specific case of a home-rolled exception ?

2008-06-27 Thread Peter Otten
Ken Starks wrote:

> I have an exception class, and I want to check that
> a particular instance of it has been raised; or
> more accurately that one is raised that is equal to
> an instance I specify.
> 
> In the example below, I can check that a
> 'LongRationalError' is raised, but I want
> to check that it is specifically a
> 'LongrationalError('1') or a 'LongRationalError('2')
> 
> How do I do that?

(all untested)

try:
LongRational(1, "7")
except LongRationalError, e:
self.assertEquals(e.code, "2")
else:
self.fail()

Alternatively you can subclass LongRationalError...

class LongRationalError(Exception):
pass

class LongRationalDenominatorError(LongRationalError):
pass

class LongRationalNumeratorError(LongRationalError):
pass

...and then check for the specialized exception:

self.assertRaises(LongRationalDenominatorError, LongRational, 1, "7")

Personally, I'd probably throw a plain old TypeError for incompatible types
of both numerator and denominator.

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


Re: where is the error?

2008-06-27 Thread lajam
There was an error with the name of the variable  I would not ask
this if it was just a question of different variable names !

diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()
new_values=values[diff_temp,:]

Okay, I'm going to try to explain that more specifically that I did. I
have an array called values (size mxn). In this database, I just want
the lines for which the values of the nth row are between two values
(it's the purpose of diff_temp). So diff_temp gets me the number of
the lines for which this latter criteria is right. But I'm interested
on the values of the lines corresponding to the number given by
diff_temp.


In matlab, I will do

diff_temp=find(values(:,5) > -2 & values[:,5) <2)

new_values=values(diff_temp,:)

Is it clear?

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


Re: How do I unit-test a specific case of a home-rolled exception ?

2008-06-27 Thread Ken Starks

Peter Otten wrote:

Ken Starks wrote:


I have an exception class, and I want to check that
a particular instance of it has been raised; or
more accurately that one is raised that is equal to
an instance I specify.

In the example below, I can check that a
'LongRationalError' is raised, but I want
to check that it is specifically a
'LongrationalError('1') or a 'LongRationalError('2')

How do I do that?


(all untested)

try:
LongRational(1, "7")
except LongRationalError, e:
self.assertEquals(e.code, "2")
else:
self.fail()

Alternatively you can subclass LongRationalError...

class LongRationalError(Exception):
pass

class LongRationalDenominatorError(LongRationalError):
pass

class LongRationalNumeratorError(LongRationalError):
pass

...and then check for the specialized exception:

self.assertRaises(LongRationalDenominatorError, LongRational, 1, "7")

Personally, I'd probably throw a plain old TypeError for incompatible types
of both numerator and denominator.

Peter


Thanks Peter, that answers my question nicely. I rather thought
I would need a try .. except structure in my unit-test itself.

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


Windows OS , Bizarre File Pointer Fact

2008-06-27 Thread Taygun Kekec
Code :
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os

if os.name == 'nt':
OS_Selection = 0
elif os.name == 'posix':
OS_Selection = 1
else :
OS_Selection = 1

del_cmd_os = ( "del","rm")
filelist = ("ddd.txt","eee.txt","fff.txt")

# Creating Files
for elem in filelist:
open( elem, 'w').write("Selam")

#
# Removing Files
for elem in filelist:
fp = open( elem, 'r')
os.system( "%s %s" % (del_cmd_os[OS_Selection], fp.name))
fp.close()
#

Run this code on Windows XP , it says "the file is being used by
another process" and fails to delete the file. I tried replacing :
#
for elem in filelist:
open( elem, 'w').write("Selam")
#
with :
#
for elem in filelist:
fp = open( elem, 'w')
fp.write("Selam")
fp.close()
#

in case of any interpreter file pointer destructor failure but it
didnt change anything.
Do you have any idea why my files cannot be deleted from my disk with
2nd part of my code ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Windows OS , Bizarre File Pointer Fact

2008-06-27 Thread Taygun Kekec
Allright i figured it out . Very stupid but very forgottable fact. I
should close the file before deleting it with shell command...
--
http://mail.python.org/mailman/listinfo/python-list


shorten path to files

2008-06-27 Thread cesco
Hi,

I need to retrieve the content of some files which are placed on a
network drive so in order to open them I need the full path to the
file.
Unfortunately some times the path is longer than 256 characters and in
Windows such a path is too long with the result that the file is not
found (though it is there).

Is there any way around this?

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


problem compiling extensions with mingw

2008-06-27 Thread eliben
Hello,
I'm trying to compile the minimal example from
http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C with
MinGW (latest version) and Python 2.5 (latest ActiveState binary
install). When running the setup file, the following happens:

running build
running build_ext
building 'hello' extension
writing build\temp.win32-2.5\Release\hello.def
d:\mingw\bin\gcc.exe -mno-cygwin -shared -s build
\temp.win32-2.5\Release\hellomo
dule.o build\temp.win32-2.5\Release\hello.def -LC:\Python25\libs -LC:
\Python25\P
Cbuild -lpython25 -lmsvcr71 -o build\lib.win32-2.5\hello.pyd
build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x3e):
undefined
 reference to `_imp___Py_NoneStruct'
build\temp.win32-2.5\Release\hellomodule.o:hellomodule.c:(.text+0x46):
undefined
 reference to `_imp___Py_NoneStruct'
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1

What's more, compiling the same extension with Visual Studio 2005
(without using distutils) works fine, the extension is loaded and ran
successfully from Python. Any ideas about this error ?

Eli

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


Re: sqlite3 alternative option

2008-06-27 Thread Carsten Haese

Uwe Grauer wrote:

I suggested Firebird because the OP asked:
 > Hi every one I'm looking for a good alternative db to replace sqlite


That he did, but people ask for what they think they need, which isn't 
always what they really need. In this particular case, sqlite was not 
the problem. The OP's suboptimal use of sqlite was the problem, and 
switching to Firebird would not have solved that problem.


--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is the error?

2008-06-27 Thread John Machin
On Jun 27, 10:12 pm, [EMAIL PROTECTED] wrote:
> There was an error with the name of the variable  I would not ask
> this if it was just a question of different variable names !
>

Calm down. Stop shouting. It is not evident whether the above means
that diff_temp_Stumpf was an error (should have been merely diff_temp)
or not.

> diff_temp=(logical_and(values[:,5] > -2,values[:,5] < 2)).nonzero()
> new_values=values[diff_temp,:]
>
> Okay, I'm going to try to explain that more specifically that I did. I
> have an array called values (size mxn). In this database, I just want
> the lines for which the values of the nth row are between two values
> (it's the purpose of diff_temp). So diff_temp gets me the number of
> the lines for which this latter criteria is right.

I think that you mean that diff_temp will be an array of the numberS
(plural) of the lines (rows?) in values array that met the -2 < x < 2
criterion. Now you want to be able to use diff_temp to get the
corresponding subset of some other array. Am I getting close?

>
 But I'm interested
> on the values of the lines corresponding to the number given by
> diff_temp.

Now you want to be able to use diff_temp to get the corresponding
subset of some other array. Am I getting close?

Perhaps you need something like other_array.take(diff_temp) ?

>
> In matlab, I will do
>
> diff_temp=find(values(:,5) > -2 & values[:,5) <2)
>
> new_values=values(diff_temp,:)
>
> Is it clear?

Not very, I don't grok matlab.

By the way, shouldn't you be using numpy? I thought numarray was going
away by mid-2008 i.e. now.

HTH,
John





> Thanks
> Cedric

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


Re: shorten path to files

2008-06-27 Thread Larry Bates

cesco wrote:

Hi,

I need to retrieve the content of some files which are placed on a
network drive so in order to open them I need the full path to the
file.
Unfortunately some times the path is longer than 256 characters and in
Windows such a path is too long with the result that the file is not
found (though it is there).

Is there any way around this?

Thanks
Francesco


You have some other problem.  The path limit of 256 characters is a DOS limit 
not a Windows limit.  You can have paths longer than 256 characters, just not in 
a command prompt window.  If not, how could the file have ever been created (you 
said the file was actually there)?


You can also map a drive to some parent folder:

net use p: \\server\folder1\folder2\folder3\folder4

then access the files relative to this drive.

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


Re: shorten path to files

2008-06-27 Thread Mike Driscoll
On Jun 27, 8:01 am, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I need to retrieve the content of some files which are placed on a
> network drive so in order to open them I need the full path to the
> file.
> Unfortunately some times the path is longer than 256 characters and in
> Windows such a path is too long with the result that the file is not
> found (though it is there).
>
> Is there any way around this?
>
> Thanks
> Francesco

Map a drive to the path or if the path is to a Linux box, create a
symbolic link.

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


Re: shorten path to files

2008-06-27 Thread A.T.Hofkamp
On 2008-06-27, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I need to retrieve the content of some files which are placed on a
> network drive so in order to open them I need the full path to the
> file.
> Unfortunately some times the path is longer than 256 characters and in
> Windows such a path is too long with the result that the file is not
> found (though it is there).
>
> Is there any way around this?

>From your description, it sounds like a OS problem, and not a Python problem.
You may have better luck if you ask in a Win* newsgroup.

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


Re: where is the error?

2008-06-27 Thread lajam

>
> I think that you mean that diff_temp will be an array of the numberS
> (plural) of the lines (rows?) in values array that met the -2 < x < 2
> criterion. Now you want to be able to use diff_temp to get the
> corresponding subset of some other array. Am I getting close?


I think that you're getting close. I want to get the lines that met
the criterion. Diff_temp is an array containing the values of the
lines. So bascially,



> Now you want to be able to use diff_temp to get the corresponding
> subset of some other array. Am I getting close?

yes


> Perhaps you need something like other_array.take(diff_temp) ?


And my problem was that the commands worked on windows but not on
linux.


> By the way, shouldn't you be using numpy? I thought numarray was going
> away by mid-2008 i.e. now.

I know, but i'm not sure that it's the problem.

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


Re: where is the error?

2008-06-27 Thread lajam

>
> I think that you mean that diff_temp will be an array of the numberS
> (plural) of the lines (rows?) in values array that met the -2 < x < 2
> criterion. Now you want to be able to use diff_temp to get the
> corresponding subset of some other array. Am I getting close?


I think that you're getting close. I want to get the lines that met
the criterion. Diff_temp is an array containing the values of the
lines. So bascially,



> Now you want to be able to use diff_temp to get the corresponding
> subset of some other array. Am I getting close?

yes


> Perhaps you need something like other_array.take(diff_temp) ?


And my problem was that the commands worked on windows but not on
linux.


> By the way, shouldn't you be using numpy? I thought numarray was going
> away by mid-2008 i.e. now.

I know, but i'm not sure that it's the problem.

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


Re: Working with the Windows Registry

2008-06-27 Thread Tim Golden

teh_sAbEr wrote:

Great! It works properly now but I have one more question, would
anyone know how to get the changes to take effect immediately? Like
some sort of Python way to force the desktop to reload? AFAIK the only
way that'll happen is if I use the Display Properties dialog box. The
Registry value is changed properly, its just I don't think the changes
will take effect until I restart.


Sorry; I missed this one earlier. One way to change the wallpaper
without delving into the registry is the SystemParametersInfo function. 
Try the following:



import win32con
import win32gui

WALLPAPER_BMP = "c:/temp/t.bmp"
win32gui.SystemParametersInfo (
   win32con.SPI_SETDESKWALLPAPER, 
   WALLPAPER_BMP, 
   win32con.SPIF_SENDCHANGE

)



The only thing I'm not sure about is whether it will survive
a logoff. If it doesn't I suppose you can always combine it
with the registry technique to make it permanent.

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


Re: where is the error?

2008-06-27 Thread lajam

>
> I think that you mean that diff_temp will be an array of the numberS
> (plural) of the lines (rows?) in values array that met the -2 < x < 2
> criterion. Now you want to be able to use diff_temp to get the
> corresponding subset of some other array. Am I getting close?


I think that you're getting close. I want to get the lines that met
the criterion. Diff_temp is an array containing the values of the
lines. So bascially,



> Now you want to be able to use diff_temp to get the corresponding
> subset of some other array. Am I getting close?

yes


> Perhaps you need something like other_array.take(diff_temp) ?


And my problem was that the commands worked on windows but not on
linux.


> By the way, shouldn't you be using numpy? I thought numarray was going
> away by mid-2008 i.e. now.

I know, but i'm not sure that it's the problem.

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


Re: where is the error?

2008-06-27 Thread lajam

>
> I think that you mean that diff_temp will be an array of the numberS
> (plural) of the lines (rows?) in values array that met the -2 < x < 2
> criterion. Now you want to be able to use diff_temp to get the
> corresponding subset of some other array. Am I getting close?


I think that you're getting close. I want to get the lines that met
the criterion. Diff_temp is an array containing the values of the
lines. So bascially,



> Now you want to be able to use diff_temp to get the corresponding
> subset of some other array. Am I getting close?

yes


> Perhaps you need something like other_array.take(diff_temp) ?


And my problem was that the commands worked on windows but not on
linux.


> By the way, shouldn't you be using numpy? I thought numarray was going
> away by mid-2008 i.e. now.

I know, but i'm not sure that it's the problem.

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


Re: shorten path to files

2008-06-27 Thread Tim Golden

On 2008-06-27, cesco <[EMAIL PROTECTED]> wrote:

Hi,

I need to retrieve the content of some files which are placed on a
network drive so in order to open them I need the full path to the
file.
Unfortunately some times the path is longer than 256 characters and in
Windows such a path is too long with the result that the file is not
found (though it is there).

Is there any way around this?


It's not clear from your description whether this applies, but there is
an API to obtain the short version of a Windows path:

http://timgolden.me.uk/pywin32-docs/win32api__GetShortPathName_meth.html

(NB this is obviously the pywin32 project; I'm simply hosting a copy
of the docs).

Also, on more recent versions of the NT family, you can map drive
letters to deep paths, you can do something like this:

NET USE * \\server\share\path1\path2\path3\path4

and then do things with x:\path5\path6\ etc.

And you may find that passing a version of the filename
as in the example below will bypass the limit anyway. Note that
this uses the \\?\ prefix.


contents = open (ur"\\?\c:\some\really\long\path").read ()



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


Re: where is the error?

2008-06-27 Thread lajam

>
> I think that you mean that diff_temp will be an array of the numberS
> (plural) of the lines (rows?) in values array that met the -2 < x < 2
> criterion. Now you want to be able to use diff_temp to get the
> corresponding subset of some other array. Am I getting close?


I think that you're getting close. I want to get the lines that met
the criterion. Diff_temp is an array containing the values of the
lines. So bascially,



> Now you want to be able to use diff_temp to get the corresponding
> subset of some other array. Am I getting close?

yes


> Perhaps you need something like other_array.take(diff_temp) ?


And my problem was that the commands worked on windows but not on
linux.


> By the way, shouldn't you be using numpy? I thought numarray was going
> away by mid-2008 i.e. now.

I know, but i'm not sure that it's the problem.

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


Simple regular expression

2008-06-27 Thread python_enthu
I am trying this.. what is wrong in this..

IDLE 1.2.2
>>> import re
>>> a="my name is fname lname"
>>> p=re.compile('name')
>>> m=p.match (a)
>>> print p.match(a)
None


findall() seems to work

>>> print p.findall(a)
['name', 'name', 'name']
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple regular expression

2008-06-27 Thread John Machin
On Jun 28, 12:00 am, python_enthu <[EMAIL PROTECTED]> wrote:
> I am trying this.. what is wrong in this..
>
> IDLE 1.2.2>>> import re
> >>> a="my name is fname lname"
> >>> p=re.compile('name')
> >>> m=p.match (a)
> >>> print p.match(a)
>
> None
>
> findall() seems to work
>
> >>> print p.findall(a)
>
> ['name', 'name', 'name']

Read the manual section on the difference between match and search.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python interface to Firefox and Thunderbird

2008-06-27 Thread yardennis
On Jun 27, 10:15 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> yardennis wrote:
> > Hi,
>
> > I need python moudles that can
>
> > auto install python 2.5 (web install or a EXE file)
>
> > auto download and install Firefox3 and Thunderbird 2
> > auto import from IE 6, 7 and OE 5,6 and Outlook
>
> > read contacts and emails from Thunderbird store
> > read Firefox 3 bookmarks, history, cookies and password
>
> > Can anyone point to a open source solution ?
>
> > If you know of any freelancer that can help me develop the module
> > please let me know.
>
> > Thanks
>
> > Dennis
> > yardennis at gmail dot com
>
> The reason you haven't gotten any responses is that you didn't provide 
> adequate
> information>
>
> You didn't say what O/S, so I have to guess that since you said Outlook it 
> must
> be windows.
>
> - Auto download and install FF3/TB2.  Why?  Dowload the installers and put 
> them
> somewhere (CD/ROM, Flash Drive, etc) , then write a batch file that installs 
> them.
>
> - Auto download and install Python.  Same as FF/TB.  Get setup.exe from
> ActiveState Python.
>
> - Auto import from IE 6, 7 and OE 5,6 and Outlook.  Auto import what into 
> what?
> Is OE Outlook Express?  What do you want to import and what are you importing 
> into?
>
> - Read contacts and emails from Thunderbird store.  Why?  Wouldn't it be 
> easier
> to read them from the POP3/IMAP server?
>
> - Read Firefox 3 bookmarks, history, cookies and password.  There are plug-ins
> that allow you to export these items (at least bookmarks and passwords).
> History/cookies can be easily cleared by the users.  If you want to monitor
> sites visited, there are better ways.
>
> As you can see we will need to know more about what you are trying to 
> accomplish
> to help more.
>
> -Larry

Larry,

Thanks for your post. Sorry for not making myself clear.

I am building for Windows first then porting to OSX and Linux later

What I need is a webinstaller or a exe file then will start
downloading Python 2.5, Firefox 3 and Thunderbird 2 and install them
into a different dir from the default install. (To prevent version
conflict)

A python script will :

using Firefox3 import feature - import all available settings from
Internet Explorer 6, 7 into Firefox 3 (password, cookies, favorites,
history)

using Thunderbird 2 import feature - import from outlook express 5,6
and Outlook into Thunderbird 2 (emails, pop, smtp, imap settings,
password, contacts)

I need python modules

to read the contacts and emails in Thunderbird 2
to create new contacts and send emails in Thunderbird 2 (just added
this)

to read the history, cookies, bookmarks, passwords stored in Firefox 3
with the cookie/password get selected web pages with urlib/urlib2
(just added this too)

These python modules will be used by a CMS(KPAX) running under web2py.

It will be good to use existing open source modules.

I am also prepared to engage a freelancer to help me develop the
modules

Thanks

Dennis





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


Re: Hamming Distance

2008-06-27 Thread Hans Terlouw

godavemon wrote:

I need to calculate the Hamming Distance of two integers.  The hamming
distance is the number of bits in two integers that don't match.
...


What about letting the bits count themselves in a parallel adding scheme:

def hamming(i, j):
   i ^= j
   i = ((i&044)>>2)+((i&0222)>>1)+(i&0111)
   i = ((i&07070707070)>>3)+(i&030707070707)
   return int(i%63)

This should work for 32-bit integers as from Python 2.4. For earlier Pythons the 
result of i^j must be positive, effectively limiting i and j to 31 bit integers.


I didn't do any speed comparisons with other methods.

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


Re: Threads, GIL and re.match() performance

2008-06-27 Thread Sebastian "lunar" Wiesner
Jeff <[EMAIL PROTECTED]>:

> (and possibly intermediate results) 
These could be stored purely in C space, without refcounting needed.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


what is meaning of "@" in pyhon program.

2008-06-27 Thread Evan
HI,

When I check example of "cmd2" module (a enhancement of cmd module), I
can not understand all, for example: the  character "@",

+
def options(option_list):
 ..

class cmd(...):
...
@options([make_option('-p', '--piglatin', action="store_true",
help="atinLay")])
+

I do not understand what "@options" does,   most time, I know what the
meaning of character "*" and character "**", but I was not use "@"
before.

Thanks for your help.

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


Use of the "is" statement

2008-06-27 Thread Joel Corbin
Hello,

I'm trying to clarify what exactly the behaviour of the is statement is (or
should be). Naturally, this has been nearly impossible to google for, even
using quotations... It is my impression that the is statement should be
equivalent to "==", at least on some level. However, this equivalency seems
to be inconsistent for reasons I can't decipher. Out of the following 3
cases, only 2 return True. What is the difference (and why is there one) in
the third case?

Python 2.5.2
>>> 'string' is 'string'   #simple assignment works
True
>>> s = 'string'
>>> s is 'string'
True
>>> def make_string():   return 'test' #but function behaviour varies
>>> def arg_to_str(arg): return str(arg)
>>> make_string() is 'test'
True
>>> arg_to_string('works') is 'works'  # this works
True
>>> arg_to_string(15) is '15'  # but this doesnt
>>> arg_to_string(15) is arg_to_string(15) # nor this!
>>> arg_to_string(15)
'15'
>>> arg_to_string(15) == arg_to_string(15)
True

This became a problem when I was using file.tell() and again when using a
custom function. If I am using is in the wrong context, what is the right
one?
Joel
--
http://mail.python.org/mailman/listinfo/python-list

Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Joel Corbin
Hi Evan,

The @ is a "decorator", knowing this should help you search for a better
explanation than I could give...

Have a look here to start:
http://mail.python.org/pipermail/tutor/2006-September/048978.html

Joel

On Fri, Jun 27, 2008 at 10:48 AM, Evan <[EMAIL PROTECTED]> wrote:

> HI,
>
> When I check example of "cmd2" module (a enhancement of cmd module), I
> can not understand all, for example: the  character "@",
>
> +
> def options(option_list):
> ..
>
> class cmd(...):
>...
>@options([make_option('-p', '--piglatin', action="store_true",
> help="atinLay")])
> +
>
> I do not understand what "@options" does,   most time, I know what the
> meaning of character "*" and character "**", but I was not use "@"
> before.
>
> Thanks for your help.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Mike Driscoll
On Jun 27, 9:48 am, Evan <[EMAIL PROTECTED]> wrote:
> HI,
>
> When I check example of "cmd2" module (a enhancement of cmd module), I
> can not understand all, for example: the  character "@",
>
> +
> def options(option_list):
>      ..
>
> class cmd(...):
>     ...
>     @options([make_option('-p', '--piglatin', action="store_true",
> help="atinLay")])
> +
>
> I do not understand what "@options" does,   most time, I know what the
> meaning of character "*" and character "**", but I was not use "@"
> before.
>
> Thanks for your help.

The "@" sign is there to signify that what follows is a decorator.
They're kind of cool and kind of confusing. Basically they dynamically
alter a function, method or class and gives them additional
functionality. It's kind of like calling a function recursively. Check
out the following links:

http://www.python.org/dev/peps/pep-0318/
http://wiki.python.org/moin/PythonDecorators
http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

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


Re: Simple regular expression

2008-06-27 Thread John Salerno
"python_enthu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I am trying this.. what is wrong in this..
>
> IDLE 1.2.2
 import re
 a="my name is fname lname"
 p=re.compile('name')
 m=p.match (a)
 print p.match(a)
> None


  match( string[, pos[, endpos]])

If zero or more characters at the beginning of string match this regular 
expression, return a corresponding MatchObject instance. Return None if the 
string does not match the pattern; note that this is different from a 
zero-length match.

  search( string[, pos[, endpos]])

Scan through string looking for a location where this regular expression 
produces a match, and return a corresponding MatchObject instance. Return 
None if no position in the string matches the pattern; note that this is 
different from finding a zero-length match at some point in the string. 


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


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Evan
cool, thanks, I will check document.

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


Re: How to get a multicast to wait for all nodes?

2008-06-27 Thread Colin J. Williams

Ryuke wrote:

I have a code that receives gps information from nodes and gives off
its own coordinates via radios connected by Ethernet.  but the code
continues to run after receiving only 1 set of coordinates, how do i
get it to wait for multiple nodes to send before continuing


You might provide wth significant part 
of the code you have written.


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


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Bruno Desthuilliers

Mike Driscoll a écrit :

On Jun 27, 9:48 am, Evan <[EMAIL PROTECTED]> wrote:

HI,

When I check example of "cmd2" module (a enhancement of cmd module), I
can not understand all, for example: the  character "@",

+
def options(option_list):
 ..

class cmd(...):
...
@options([make_option('-p', '--piglatin', action="store_true",
help="atinLay")])
+

I do not understand what "@options" does,   most time, I know what the
meaning of character "*" and character "**", but I was not use "@"
before.

Thanks for your help.


The "@" sign is there to signify that what follows is a decorator.
They're kind of cool and kind of confusing. Basically they dynamically
alter a function, method or class and gives them additional
functionality. It's kind of like calling a function recursively.


Mostly, it's just syntactic sugar for an higher order function. IOW, given:

def deco(func):
   # do anythin you wish here
   # and return any callable object
   return any_callable_object

the two following syntaxes are equivalent:

def toto():
pass
toto = deco(toto)

@deco
def toto():
pass

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


embedding and extending python C API registering callback handler objects

2008-06-27 Thread Tim Spens
Hello all,

I've been trying to get an example found here 
http://codeidol.com/python/python3/Embedding-Python/Registering-Callback-Handler-Objects/
 
to work.  Every thing works fine except when I try to trigger an event from c 
that will call a python function.  Here is my test code:

//---python code--//
#! /usr/bin/env python
import time
import callback

def callback1(label,count):
print 'callback1 successfully triggered from python via callback.so'
return 'callback1 => %s number %i' % (label, count)

def callback2(label,count):
return 'callback2 => ' +  label * count

print '\nTest1:'
callback.setHandler(callback1)
callback.triggerEvent() # simulate events caught by C layer

print '\nTest2:'
callback.setHandler(callback2)

print 'Waiting for callback2 to be called from c:'
while 1:
time.sleep(.001)

//---c code---//
#include 
#include 

/* keep Python object in C */
static PyObject *Handler = NULL;

void Route_Event(char *label, int count){
char *cres;
PyObject *args, *pres;
/* call Python handler */
args = Py_BuildValue("(si)", label, count);
pres = PyEval_CallObject(Handler, args);
Py_DECREF(args);
if (pres != NULL){
/* use and decref handler result */
PyArg_Parse(pres, "s", &cres);
printf("%s\n", cres);
Py_DECREF(pres);
}}

// the actual python callback call
static PyObject *
make_call(PyObject *function, PyObject *args){
if (function == NULL) return NULL;
PyObject * val = PyObject_CallObject(function, args);
Py_XDECREF(args);
return val;
}

static PyObject *
Register_Handler(PyObject *self, PyObject *args){
/* save Python callable object */
Py_XDECREF(Handler);
PyArg_Parse(args, "O", &Handler);
Py_XINCREF(Handler);
Py_INCREF(Py_None);
return Py_None;
}

static PyObject *
Trigger_Event(PyObject *self, PyObject *args){
/* let Python simulate event caught by C */
static int count = 0;
Route_Event("spam", count++);
Py_INCREF(Py_None);
return Py_None;
}

static struct PyMethodDef callback_methods[] = {
{"setHandler",Register_Handler},   /* name, address */
{"triggerEvent",  Trigger_Event},
{NULL, NULL}
};
  /* on first "import callback" */
void initcallback(){  /* this is called by Python  */
(void) Py_InitModule("callback", callback_methods);
}

int main(){
while (1){
printf("1\n");
//attempting to call callback2 which is registered to Handler
//i've also tried args = Py_BuildValue("(si)", label, count); 
here but I get a segfault.
PyObject *args = Py_BuildValue("s","c code");
printf("2\n");
PyObject* val = make_call(Handler,args);
printf("3\n");
Py_XDECREF (val);
printf("4\n");
sleep(1);
}}

//compiler stuff--//
gcc callback.c -c -g -Wall -fpic -I /usr/include/python2.5 -o callback.o
gcc callback.c -g -Wall -I /usr/include/python2.5 -L /usr/local/lib -lpython2.5 
-o callback
gcc -shared -Wall callback.o -o callback.so

//test code results---//
../callback.py 
Test1:
callback1 successfully triggered from python via callback.so
callback1 => spam number 0

Test2:
Waiting for callback2 to be called from c:
#NOTHING EVER GETS PRINTED HERE CALLBACK NEVER GETS CALLED?

../callback
1
2
3
4


Thanks,
Tim


  

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


Re: Design principles and architecture of an information transfer standard based on XML and SOAP

2008-06-27 Thread Stefan Behnel
xkenneth wrote:
> I'm looking for a bit of advice. There's an oilfield standard
> called WITSML (Wellsite Information Transfer Standard Markup Language
> - witsml.org), it's basically a collection of XML schemas and a spec

For implementing XML languages, I (biasedly) advocate lxml's element class
features.

http://codespeak.net/lxml/dev/element_classes.html

I'll give a tutorial on them at EuroPython, in case you're interested.

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


Re: Use of the "is" statement

2008-06-27 Thread Gary Herron

Joel Corbin wrote:

Hello,

I'm trying to clarify what exactly the behaviour of the is statement 
is (or should be). Naturally, this has been nearly impossible to 
google for, even using quotations... It is my impression that the is 
statement should be equivalent to "==", at least on some level. 
However, this equivalency seems to be inconsistent for reasons I can't 
decipher. Out of the following 3 cases, only 2 return True. What is 
the difference (and why is there one) in the third case?


Comparing two numbers or strings with "is" is equivalent to asking if 
the two numbers or strings are stored in the same location in memory.  
But since you have no control where values are stored when you bind them 
to a name, this is completely pointless.


In
 a=15
 b=15
it is implementation dependent whether the value 15 is stored once and 
refereed to twice, or stored twice. 


In short:  *never* use "is".

(A longer answer can find some uses cases for "is", but stick with the 
short answer for now.)


Gary Herron



Python 2.5.2
>>> 'string' is 'string'   #simple assignment works
True
>>> s = 'string'  
>>> s is 'string'
True

>>> def make_string():   return 'test' #but function behaviour varies
>>> def arg_to_str(arg): return str(arg)
>>> make_string() is 'test'
True
>>> arg_to_string('works') is 'works'  # this works
True
>>> arg_to_string(15) is '15'  # but this doesnt
>>> arg_to_string(15) is arg_to_string(15) # nor this!
>>> arg_to_string(15)
'15'
>>> arg_to_string(15) == arg_to_string(15)
True

This became a problem when I was using file.tell() and again when 
using a custom function. If I am using is in the wrong context, what 
is the right one?

Joel



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


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


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Damon Getsman
Okay, maybe I just didn't understand the websites that were given as
examples as to 'decoration'.  I first came across the unusual '@' when
I was browsing through some extreme beginner's information on os.x
method descriptions.  I asked some other people about it and they had
no idea what it meant.  I don't _THINK_ that the decoration definition
fits, though, because the examples that I saw it in had it prefixing
an if conditional & a for loop.

ie:
@if os.exists(foo):
   etc
   etc

and

@for blah:
   etc
   etc

does this mean that the person writing the script defined a function
instead of the standard conditional and loop?  I can't imagine that
would be the case because, as I said, this was very beginning level
documentation.

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


Re: Use of the "is" statement

2008-06-27 Thread Christian Heimes
Joel Corbin wrote:
> I'm trying to clarify what exactly the behaviour of the is statement is (or
> should be).  ...

People often think that "is" is part of the comparison operator set. The
"is" statement does not compare two objects. Never ever use "is" to
compare strings or numbers.

Christian


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


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Bruno Desthuilliers

Damon Getsman a écrit :

Okay, maybe I just didn't understand the websites that were given as
examples as to 'decoration'.  I first came across the unusual '@' when
I was browsing through some extreme beginner's information on os.x
method descriptions.  I asked some other people about it and they had
no idea what it meant.  I don't _THINK_ that the decoration definition
fits, though, because the examples that I saw it in had it prefixing
an if conditional & a for loop.

ie:
@if os.exists(foo):
   etc
   etc

and

@for blah:
   etc
   etc


This is not valid Python. period.


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


Re: Use of the "is" statement

2008-06-27 Thread Cédric Lucantis
Le Friday 27 June 2008 16:51:07 Joel Corbin, vous avez écrit :
> Hello,
>
> I'm trying to clarify what exactly the behaviour of the is statement is (or
> should be). Naturally, this has been nearly impossible to google for, even
> using quotations... 

try this one:

http://www.google.com/search?hl=en&q=python+identity&btnG=Google+Search&aq=-1&oq=

or this one if you still don't get it :)

http://en.wikipedia.org/wiki/Image:MagrittePipe.jpg

> This became a problem when I was using file.tell() and again when using a
> custom function. If I am using is in the wrong context, what is the right
> one?

What problems did you have exactly ?

-- 
Cédric Lucantis
--
http://mail.python.org/mailman/listinfo/python-list

Re: Use of the "is" statement

2008-06-27 Thread Christian Heimes
Gary Herron wrote:
> In short:  *never* use "is".

Never use "is" unless you want to check "if something is None or
something is not None"

Christian

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


Re: Use of the "is" statement

2008-06-27 Thread Joel Corbin
Thank you Gary, Cédric, Christian. When *would *one use "is"?

Cédric... the problem I was having was purely an issue of comparison "if
file.tell() is 0L" was returning False. Strangely enough, "if file.tell() is
0" returns True in the right cases. I assume this is related to the None
case?

On Fri, Jun 27, 2008 at 11:47 AM, Christian Heimes <[EMAIL PROTECTED]> wrote:

> Gary Herron wrote:
> > In short:  *never* use "is".
>
> Never use "is" unless you want to check "if something is None or
> something is not None"
>
> Christian
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Use of the "is" statement

2008-06-27 Thread Jason Scheirer
On Jun 27, 8:38 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Joel Corbin wrote:
> > Hello,
>
> > I'm trying to clarify what exactly the behaviour of the is statement
> > is (or should be). Naturally, this has been nearly impossible to
> > google for, even using quotations... It is my impression that the is
> > statement should be equivalent to "==", at least on some level.
> > However, this equivalency seems to be inconsistent for reasons I can't
> > decipher. Out of the following 3 cases, only 2 return True. What is
> > the difference (and why is there one) in the third case?
>
> Comparing two numbers or strings with "is" is equivalent to asking if
> the two numbers or strings are stored in the same location in memory.  
> But since you have no control where values are stored when you bind them
> to a name, this is completely pointless.
>
> In
>   a=15
>   b=15
> it is implementation dependent whether the value 15 is stored once and
> refereed to twice, or stored twice.
>
> In short:  *never* use "is".
>
> (A longer answer can find some uses cases for "is", but stick with the
> short answer for now.)
>
> Gary Herron
>
>
>
> > Python 2.5.2
> > >>> 'string' is 'string'                   #simple assignment works
> > True
> > >>> s = 'string'      
> > >>> s is 'string'        
> > True
> > >>> def make_string():   return 'test'     #but function behaviour varies
> > >>> def arg_to_str(arg): return str(arg)
> > >>> make_string() is 'test'
> > True
> > >>> arg_to_string('works') is 'works'      # this works
> > True
> > >>> arg_to_string(15) is '15'              # but this doesnt
> > >>> arg_to_string(15) is arg_to_string(15) # nor this!
> > >>> arg_to_string(15)
> > '15'
> > >>> arg_to_string(15) == arg_to_string(15)
> > True
>
> > This became a problem when I was using file.tell() and again when
> > using a custom function. If I am using is in the wrong context, what
> > is the right one?
> > Joel
>
> > 
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

Is is identity, not equality. It's the equivalent of comparing two
pointers' addresses in C.

You can get the memory location of an object x in python using the
id() function, so remember the following:

a is b

IS THE SAME THING AS

id(a) == id(b)

The reason 'is' works for things like 'a is None' is because there is
only one None builtin in memory ever, all the variables assigned to
none merely point at it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: embedding and extending python C API registering callback handler objects

2008-06-27 Thread Matimus
On Jun 27, 8:22 am, Tim Spens <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I've been trying to get an example found 
> herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb...
> to work.  Every thing works fine except when I try to trigger an event from c 
> that will call a python function.  Here is my test code:
>
> //---python code--//
> #! /usr/bin/env python
> import time
> import callback
>
> def callback1(label,count):
>         print 'callback1 successfully triggered from python via callback.so'
>         return 'callback1 => %s number %i' % (label, count)
>
> def callback2(label,count):
>         return 'callback2 => ' +  label * count
>
> print '\nTest1:'
> callback.setHandler(callback1)
> callback.triggerEvent()         # simulate events caught by C layer
>
> print '\nTest2:'
> callback.setHandler(callback2)
>
> print 'Waiting for callback2 to be called from c:'
> while 1:
>         time.sleep(.001)
>
> //---c code---//
> #include 
> #include 
>
> /* keep Python object in C */
> static PyObject *Handler = NULL;
>
> void Route_Event(char *label, int count){
>     char *cres;
>     PyObject *args, *pres;
>     /* call Python handler */
>     args = Py_BuildValue("(si)", label, count);
>     pres = PyEval_CallObject(Handler, args);
>     Py_DECREF(args);
>     if (pres != NULL){
>         /* use and decref handler result */
>         PyArg_Parse(pres, "s", &cres);
>         printf("%s\n", cres);
>         Py_DECREF(pres);
>
> }}
>
> // the actual python callback call
> static PyObject *
> make_call(PyObject *function, PyObject *args){
>     if (function == NULL) return NULL;
>     PyObject * val = PyObject_CallObject(function, args);
>     Py_XDECREF(args);
>     return val;
>
> }
>
> static PyObject *
> Register_Handler(PyObject *self, PyObject *args){
>     /* save Python callable object */
>     Py_XDECREF(Handler);
>     PyArg_Parse(args, "O", &Handler);
>     Py_XINCREF(Handler);
>     Py_INCREF(Py_None);
>     return Py_None;
>
> }
>
> static PyObject *
> Trigger_Event(PyObject *self, PyObject *args){
>     /* let Python simulate event caught by C */
>     static int count = 0;
>     Route_Event("spam", count++);
>     Py_INCREF(Py_None);
>     return Py_None;
>
> }
>
> static struct PyMethodDef callback_methods[] = {
>     {"setHandler",    Register_Handler},       /* name, address */
>     {"triggerEvent",  Trigger_Event},
>     {NULL, NULL}};
>
>                                       /* on first "import callback" */
> void initcallback(){                  /* this is called by Python  */
>     (void) Py_InitModule("callback", callback_methods);
>
> }
>
> int main(){
>         while (1){
>                 printf("1\n");
>                 //attempting to call callback2 which is registered to Handler
>                 //i've also tried args = Py_BuildValue("(si)", label, count); 
> here but I get a segfault.
>                 PyObject *args = Py_BuildValue("s","c code");
>                 printf("2\n");
>                 PyObject* val = make_call(Handler,args);
>                 printf("3\n");
>             Py_XDECREF (val);
>             printf("4\n");
>                 sleep(1);
>
> }}
>
> //compiler stuff--//
> gcc callback.c -c -g -Wall -fpic -I /usr/include/python2.5 -o callback.o
> gcc callback.c -g -Wall -I /usr/include/python2.5 -L /usr/local/lib 
> -lpython2.5 -o callback
> gcc -shared -Wall callback.o -o callback.so
>
> //test code results---//
> ../callback.py
> Test1:
> callback1 successfully triggered from python via callback.so
> callback1 => spam number 0
>
> Test2:
> Waiting for callback2 to be called from c:
> #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER GETS CALLED?
>
> ../callback
> 1
> 2
> 3
> 4
> 
>
> Thanks,
> Tim

Maybe you just need to flush the stdout buffer in python.
`sys.stdout.flush()`

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


How do web templates separate content and logic?

2008-06-27 Thread John Salerno
I've been doing some research on web templates, and even though I read that 
they help enforce the MVC pattern, I don't really understand how they are 
keeping content and logic separated. Layout is easy, it's just not there as 
far as I can see, and CSS can be used for that.

But when you have a templating system that mixes HTML and Python code, how 
is this helping to keep things separate? It seems to be the same issue that 
some people have with PHP (that it is too integrated with the HTML, rather 
than being separate).

Of course, I suppose whether or not any of this matters depends on if you 
are a web designer or a programmer, but am I missing something about 
templates, or is it really the case that they, more or less by definition, 
combine content and logic?

Thanks. 


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


Re: How to "rebind" py2.5.1 to run from comprompt after uninstalling py3.0?

2008-06-27 Thread Matimus
On Jun 26, 8:13 pm, defn noob <[EMAIL PROTECTED]> wrote:
> I installed python30 and so command prompt runs all pythonprograms
> through that which i didnt want so i uninstalled it.
>
> now i cant start any pythonprograms through the commandprompt.
>
> how do I "rebind" python25 to luanch when claling .py-files from the
> command prompt?

I'm assuming you are using Windows? You should be able to just re-
install python 2.5.2 (latest version would be good) over the top. It
won't destroy any 3rd party modules you have installed. The only thing
you could lose would be if you had modified something in the standard
library, which is a bad idea anyway.

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


Re: embedding and extending python C API registering callback handler objects

2008-06-27 Thread Tim Spens
thanks, but didn't fix the problem.


--- On Fri, 6/27/08, Matimus <[EMAIL PROTECTED]> wrote:

> From: Matimus <[EMAIL PROTECTED]>
> Subject: Re: embedding and extending python C API registering callback 
> handler objects
> To: python-list@python.org
> Date: Friday, June 27, 2008, 9:03 AM
> On Jun 27, 8:22 am, Tim Spens <[EMAIL PROTECTED]>
> wrote:
> > Hello all,
> >
> > I've been trying to get an example found
> herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb...
> > to work.  Every thing works fine except when I try to
> trigger an event from c that will call a python function.
>  Here is my test code:
> >
> > //---python
> code--//
> > #! /usr/bin/env python
> > import time
> > import callback
> >
> > def callback1(label,count):
> > print 'callback1 successfully
> triggered from python via callback.so'
> > return 'callback1 => %s number
> %i' % (label, count)
> >
> > def callback2(label,count):
> > return 'callback2 => ' +
>  label * count
> >
> > print '\nTest1:'
> > callback.setHandler(callback1)
> > callback.triggerEvent() # simulate events
> caught by C layer
> >
> > print '\nTest2:'
> > callback.setHandler(callback2)
> >
> > print 'Waiting for callback2 to be called from
> c:'
> > while 1:
> > time.sleep(.001)
> >
> > //---c
> code---//
> > #include 
> > #include 
> >
> > /* keep Python object in C */
> > static PyObject *Handler = NULL;
> >
> > void Route_Event(char *label, int count){
> > char *cres;
> > PyObject *args, *pres;
> > /* call Python handler */
> > args = Py_BuildValue("(si)", label,
> count);
> > pres = PyEval_CallObject(Handler, args);
> > Py_DECREF(args);
> > if (pres != NULL){
> > /* use and decref handler result */
> > PyArg_Parse(pres, "s",
> &cres);
> > printf("%s\n", cres);
> > Py_DECREF(pres);
> >
> > }}
> >
> > // the actual python callback call
> > static PyObject *
> > make_call(PyObject *function, PyObject *args){
> > if (function == NULL) return NULL;
> > PyObject * val = PyObject_CallObject(function,
> args);
> > Py_XDECREF(args);
> > return val;
> >
> > }
> >
> > static PyObject *
> > Register_Handler(PyObject *self, PyObject *args){
> > /* save Python callable object */
> > Py_XDECREF(Handler);
> > PyArg_Parse(args, "O", &Handler);
> > Py_XINCREF(Handler);
> > Py_INCREF(Py_None);
> > return Py_None;
> >
> > }
> >
> > static PyObject *
> > Trigger_Event(PyObject *self, PyObject *args){
> > /* let Python simulate event caught by C */
> > static int count = 0;
> > Route_Event("spam", count++);
> > Py_INCREF(Py_None);
> > return Py_None;
> >
> > }
> >
> > static struct PyMethodDef callback_methods[] = {
> > {"setHandler",Register_Handler},
>   /* name, address */
> > {"triggerEvent",  Trigger_Event},
> > {NULL, NULL}};
> >
> >
>   /* on first "import callback" */
> > void initcallback(){  /* this
> is called by Python  */
> > (void) Py_InitModule("callback",
> callback_methods);
> >
> > }
> >
> > int main(){
> > while (1){
> > printf("1\n");
> > //attempting to call callback2
> which is registered to Handler
> > //i've also tried args =
> Py_BuildValue("(si)", label, count); here but I
> get a segfault.
> > PyObject *args =
> Py_BuildValue("s","c code");
> > printf("2\n");
> > PyObject* val =
> make_call(Handler,args);
> > printf("3\n");
> > Py_XDECREF (val);
> > printf("4\n");
> > sleep(1);
> >
> > }}
> >
> > //compiler
> stuff--//
> > gcc callback.c -c -g -Wall -fpic -I
> /usr/include/python2.5 -o callback.o
> > gcc callback.c -g -Wall -I /usr/include/python2.5 -L
> /usr/local/lib -lpython2.5 -o callback
> > gcc -shared -Wall callback.o -o callback.so
> >
> > //test code
> results---//
> > ../callback.py
> > Test1:
> > callback1 successfully triggered from python via
> callback.so
> > callback1 => spam number 0
> >
> > Test2:
> > Waiting for callback2 to be called from c:
> > #NOTHING EVER GETS PRINTED HERE CALLBACK NEVER GETS
> CALLED?
> >
> > ../callback
> > 1
> > 2
> > 3
> > 4
> > 
> >
> > Thanks,
> > Tim
> 
> Maybe you just need to flush the stdout buffer in python.
> `sys.stdout.flush()`
> 
> Matt
> --
> http://mail.python.org/mailman/listinfo/python-list


  

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


Re: newb question on strings

2008-06-27 Thread Kirk Strauser
At 2008-06-24T20:27:33Z, regex_jedi <[EMAIL PROTECTED]> writes:

> Notice that the 4th value has a single quote in it. Well, I need to
> make sure that the single quote is escaped before handing it off for
> further processing to a class I later call for some other processing.

Out of curiosity, what kind of processing?  The only time I've really had to
mess with escaping quotes involved SQL.  There is *no* reason why you'd ever
directly generate SQL strings yourself today unless you're writing a
database connector.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread John Salerno
"Damon Getsman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Okay, maybe I just didn't understand the websites that were given as
> examples as to 'decoration'.  I first came across the unusual '@' when
> I was browsing through some extreme beginner's information on os.x
> method descriptions.  I asked some other people about it and they had
> no idea what it meant.  I don't _THINK_ that the decoration definition
> fits, though, because the examples that I saw it in had it prefixing
> an if conditional & a for loop.

The OP's code sample makes sense for decorators, I think. Can you post an 
actual sample of what it is you saw? Sounds weird. 


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


Re: How do web templates separate content and logic?

2008-06-27 Thread Sebastian "lunar" Wiesner
John Salerno <[EMAIL PROTECTED]>:

> But when you have a templating system that mixes HTML and Python code, how
> is this helping to keep things separate? 

You don't.  Normally you embed only the code, that is absolutely necessary,
e.g. for iterating over a list.

Consider an online shop, that needs to do display a list of articles. 
Inside the template, you would iterate over a list of and query attributes
of "Article" object to render the information as HTML.  You would _not_
create a database connection, parse search parameters, find matching
articles and create a list of them.  That's the job of the controller
inside the web app.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Use of the "is" statement

2008-06-27 Thread Christian Heimes
Joel Corbin wrote:
> Thank you Gary, Cédric, Christian. When *would *one use "is"?

As I said:
The "is" statement should only be used when you want to check of
something is exactly and identical to None like "a is None" or "b is not
None". For everything else you should use == or !=. There are some other
use cases for "is", too. But in general you shouldn't use "is".

> Cédric... the problem I was having was purely an issue of comparison "if
> file.tell() is 0L" was returning False. Strangely enough, "if file.tell() is
> 0" returns True in the right cases. I assume this is related to the None
> case?

Both usages of "is" are wrong. The second case works by accident,
because Python optimized small ints. The int object 0 and some more
objects are a singletons.

Ask yourself if you are interested if f.tell() returns exactly the same
0 object ("is") or a number that is equal to 0 ("==").

Christian

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


Re: Simple regular expression

2008-06-27 Thread python_enthu
On Jun 27, 11:05 am, "John Salerno" <[EMAIL PROTECTED]> wrote:
> "python_enthu" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> >I am trying this.. what is wrong in this..
>
> > IDLE 1.2.2
>  import re
>  a="my name is fname lname"
>  p=re.compile('name')
>  m=p.match (a)
>  print p.match(a)
> > None
>
>       match( string[, pos[, endpos]])
>
> If zero or more characters at the beginning of string match this regular
> expression, return a corresponding MatchObject instance. Return None if the
> string does not match the pattern; note that this is different from a
> zero-length match.
>
>       search( string[, pos[, endpos]])
>
> Scan through string looking for a location where this regular expression
> produces a match, and return a corresponding MatchObject instance. Return
> None if no position in the string matches the pattern; note that this is
> different from finding a zero-length match at some point in the string.

Thanks John Salerno and John Machin,

I am used to perl. So I guess I am better of using re.search instead
of re.match
BTW, is re.search('string') equivalent to re.match ('^string')

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


Re: Use of the "is" statement

2008-06-27 Thread Maric Michaud
Le Friday 27 June 2008 18:26:45 Christian Heimes, vous avez écrit :
> Ask yourself if you are interested if f.tell() returns exactly the same
> 0 object ("is") or a number that is equal to 0 ("==").

That said, "f.tell() == 0" and "f.tell() != 0" should be written "f.tell()" 
and "not f.tell()" in python.

if not f.tell() :
print 'at the beginning of the file"


-- 
_

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


Re: what is meaning of "@" in pyhon program.

2008-06-27 Thread Damon Getsman
I didn't think that it was.  I just spent about 10 minutes trying to
google for the page that I found that on, but I wasn't able to turn it
up.  My google-fu sucks.  I know that I was researching a particular
part of the os module and that the snippets of script on the page had
an example containing '@if' and '@for'.  I don't remember what exactly
I used to turn it up before, though, and the link isn't in my history,
it was probably a month ago that I saw it.

Sorry, I tried.

On Jun 27, 10:44 am, Bruno Desthuilliers  wrote:
> Damon Getsman a écrit :
> > ie:
> > @if os.exists(foo):
> >    etc
> >    etc
>
> > and
>
> > @for blah:
> >    etc
> >    etc
>
> This is not valid Python. period.

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


Using Python Scripts with IIS - ASP or Python-based CGI scripts with IIS - which makes more sense?

2008-06-27 Thread davidj411
when does is make sense to use a ASP style Page (.psp) over a Python-
based CGI script with IIS.
?

http://support.microsoft.com/kb/276494

ASP requires registering the python engine.

which has better performance?
The ASP style uses a new part of the python language which is
unfamiliar to me, e.g. "Response.Write('Python Test')" . Where can
i learn about the syntax for ASP (PSP) with Python?

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


Re: Windows OS , Bizarre File Pointer Fact

2008-06-27 Thread Matt Nordhoff
Taygun Kekec wrote:
> Code :
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> import os
> 
> if os.name == 'nt':
> OS_Selection = 0
> elif os.name == 'posix':
> OS_Selection = 1
> else :
> OS_Selection = 1
> 
> del_cmd_os = ( "del","rm")
> filelist = ("ddd.txt","eee.txt","fff.txt")
> 
> # Creating Files
> for elem in filelist:
> open( elem, 'w').write("Selam")
> 
> #
> # Removing Files
> for elem in filelist:
> fp = open( elem, 'r')
> os.system( "%s %s" % (del_cmd_os[OS_Selection], fp.name))
> fp.close()
> #
> 
> Run this code on Windows XP , it says "the file is being used by
> another process" and fails to delete the file. I tried replacing :
> #
> for elem in filelist:
> open( elem, 'w').write("Selam")
> #
> with :
> #
> for elem in filelist:
> fp = open( elem, 'w')
> fp.write("Selam")
> fp.close()
> #
> 
> in case of any interpreter file pointer destructor failure but it
> didnt change anything.
> Do you have any idea why my files cannot be deleted from my disk with
> 2nd part of my code ?

Why are you executing another program just to delete a file?

>>> import os
>>> os.remove('some/file.txt')
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: embedding and extending python C API registering callback handler objects

2008-06-27 Thread Tim Spens



--- On Fri, 6/27/08, Tim Spens <[EMAIL PROTECTED]> wrote:

> From: Tim Spens <[EMAIL PROTECTED]>
> Subject: Re: embedding and extending python C API registering callback 
> handler objects
> To: python-list@python.org, "Matimus" <[EMAIL PROTECTED]>
> Date: Friday, June 27, 2008, 9:16 AM
> thanks, but didn't fix the problem.
> 
> 
> --- On Fri, 6/27/08, Matimus <[EMAIL PROTECTED]>
> wrote:
> 
> > From: Matimus <[EMAIL PROTECTED]>
> > Subject: Re: embedding and extending python C API
> registering callback handler objects
> > To: python-list@python.org
> > Date: Friday, June 27, 2008, 9:03 AM
> > On Jun 27, 8:22 am, Tim Spens
> <[EMAIL PROTECTED]>
> > wrote:
> > > Hello all,
> > >
> > > I've been trying to get an example found
> >
> herehttp://codeidol.com/python/python3/Embedding-Python/Registering-Callb...
> > > to work.  Every thing works fine except when I
> try to
> > trigger an event from c that will call a python
> function.
> >  Here is my test code:
> > >
> > > //---python
> > code--//
> > > #! /usr/bin/env python
> > > import time
> > > import callback
> > >
> > > def callback1(label,count):
> > > print 'callback1 successfully
> > triggered from python via callback.so'
> > > return 'callback1 => %s number
> > %i' % (label, count)
> > >
> > > def callback2(label,count):
> > > return 'callback2 => ' +
> >  label * count
> > >
> > > print '\nTest1:'
> > > callback.setHandler(callback1)
> > > callback.triggerEvent() # simulate events
> > caught by C layer
> > >
> > > print '\nTest2:'
> > > callback.setHandler(callback2)
> > >
> > > print 'Waiting for callback2 to be called
> from
> > c:'
> > > while 1:
> > > time.sleep(.001)
> > >
> > > //---c
> > code---//
> > > #include 
> > > #include 
> > >
> > > /* keep Python object in C */
> > > static PyObject *Handler = NULL;
> > >
> > > void Route_Event(char *label, int count){
> > > char *cres;
> > > PyObject *args, *pres;
> > > /* call Python handler */
> > > args = Py_BuildValue("(si)", label,
> > count);
> > > pres = PyEval_CallObject(Handler, args);
> > > Py_DECREF(args);
> > > if (pres != NULL){
> > > /* use and decref handler result */
> > > PyArg_Parse(pres, "s",
> > &cres);
> > > printf("%s\n", cres);
> > > Py_DECREF(pres);
> > >
> > > }}
> > >
> > > // the actual python callback call
> > > static PyObject *
> > > make_call(PyObject *function, PyObject *args){
> > > if (function == NULL) return NULL;
> > > PyObject * val =
> PyObject_CallObject(function,
> > args);
> > > Py_XDECREF(args);
> > > return val;
> > >
> > > }
> > >
> > > static PyObject *
> > > Register_Handler(PyObject *self, PyObject *args){
> > > /* save Python callable object */
> > > Py_XDECREF(Handler);
> > > PyArg_Parse(args, "O",
> &Handler);
> > > Py_XINCREF(Handler);
> > > Py_INCREF(Py_None);
> > > return Py_None;
> > >
> > > }
> > >
> > > static PyObject *
> > > Trigger_Event(PyObject *self, PyObject *args){
> > > /* let Python simulate event caught by C */
> > > static int count = 0;
> > > Route_Event("spam", count++);
> > > Py_INCREF(Py_None);
> > > return Py_None;
> > >
> > > }
> > >
> > > static struct PyMethodDef callback_methods[] = {
> > > {"setHandler",   
> Register_Handler},
> >   /* name, address */
> > > {"triggerEvent",  Trigger_Event},
> > > {NULL, NULL}};
> > >
> > >
> >   /* on first "import callback" */
> > > void initcallback(){  /* this
> > is called by Python  */
> > > (void) Py_InitModule("callback",
> > callback_methods);
> > >
> > > }
> > >
> > > int main(){
> > > while (1){
> > > printf("1\n");
> > > //attempting to call callback2
> > which is registered to Handler
> > > //i've also tried args =
> > Py_BuildValue("(si)", label, count); here
> but I
> > get a segfault.
> > > PyObject *args =
> > Py_BuildValue("s","c code");
> > > printf("2\n");
> > > PyObject* val =
> > make_call(Handler,args);
> > > printf("3\n");
> > > Py_XDECREF (val);
> > > printf("4\n");
> > > sleep(1);
> > >
> > > }}
> > >
> > > //compiler
> > stuff--//
> > > gcc callback.c -c -g -Wall -fpic -I
> > /usr/include/python2.5 -o callback.o
> > > gcc callback.c -g -Wall -I /usr/include/python2.5
> -L
> > /usr/local/lib -lpython2.5 -o callback
> > > gcc -shared -Wall callback.o -o callback.so
> > >
> > > //test code
> > results---//
> > > ../callback.py
> > > Test1:
> > > callback1 successfully triggered from python via
> > callback.so
> > > callback1 => spam number 0
> > >
> > > Test2:
> > > Waiting for callback2 to be called fro

Django or TurboGears for a new project

2008-06-27 Thread Kirk Strauser
We're looking to migrate a Zope site to Django, but before getting beyond
the dreaming stage, I thought I'd see what others are doing these days.

If you were going to start a fairly complex site today with lots of DB
integration, would you begin with Django or TurboGears, or something else
entirely?

I'm more interested in social, rather than technical reasons (unless there's
something you absolutely love or despise about one or the other).
Popularity is actually a pretty big consideration because I'd like to work
with an eager community who's doing cool new things.

I know asking for comparisons like this is potentially flamebait-ish, but I
really don't mean it that way.  It's just that I don't have a lot of friends
in the industry in this particular development niche who I can ask for
recommendations, and this seems like as good a place as any to find subject
matter experts.

Thanks,
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple regular expression

2008-06-27 Thread Joel Corbin
If you read John's message carefully (which is the output of
"help(re.search)") you can see the difference between "re.search" and
"re.match". The former looks for a regex anywhere in the given string, the
latter requires the string to begin with the given regex.

Joel

On Fri, Jun 27, 2008 at 12:26 PM, python_enthu <[EMAIL PROTECTED]> wrote:

> On Jun 27, 11:05 am, "John Salerno" <[EMAIL PROTECTED]> wrote:
> > "python_enthu" <[EMAIL PROTECTED]> wrote in message
> >
> > news:[EMAIL PROTECTED]
> ..
> >
> > >I am trying this.. what is wrong in this..
> >
> > > IDLE 1.2.2
> >  import re
> >  a="my name is fname lname"
> >  p=re.compile('name')
> >  m=p.match (a)
> >  print p.match(a)
> > > None
> >
> >   match( string[, pos[, endpos]])
> >
> > If zero or more characters at the beginning of string match this regular
> > expression, return a corresponding MatchObject instance. Return None if
> the
> > string does not match the pattern; note that this is different from a
> > zero-length match.
> >
> >   search( string[, pos[, endpos]])
> >
> > Scan through string looking for a location where this regular expression
> > produces a match, and return a corresponding MatchObject instance. Return
> > None if no position in the string matches the pattern; note that this is
> > different from finding a zero-length match at some point in the string.
>
> Thanks John Salerno and John Machin,
>
> I am used to perl. So I guess I am better of using re.search instead
> of re.match
> BTW, is re.search('string') equivalent to re.match ('^string')
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: sqlite3 alternative option

2008-06-27 Thread Petite Abeille


On Jun 26, 2008, at 10:55 PM, Gandalf wrote:


I have almost million records so I need a better solution.



SQLite shouldn't have any issue handling such a load. Perhaps this is  
an operator, hmmm, issue?


--
PA.
http://alt.textdrive.com/nanoki/
--
http://mail.python.org/mailman/listinfo/python-list


Re: ask for a RE pattern to match TABLE in html

2008-06-27 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 Jonathan Gardner <[EMAIL PROTECTED]> wrote:

> On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote:
> > Try something like:
> >
> > re.compile(r'.*?', re.DOTALL)
> 
> So you would pick up strings like "foo td>"? I doubt that is what oyster wants.

I asked a question recently - nobody answered, I think
because they assumed it was just a rhetorical question:

(i) It's true, isn't it, that it's impossible for the
formal CS notion of "regular expression" to correctly
parse nested open/close delimiters?

(ii) The regexes in languages like Python and Perl include
features that are not part of the formal CS notion of
"regular expression". Do they include something that
does allow parsing nested delimiters properly?

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list

Re: using urllib2

2008-06-27 Thread Alexnb

Okay, I tried to follow that, and it is kinda hard. But since you obviously
know what you are doing, where did you learn this? Or where can I learn
this?


Maric Michaud wrote:
> 
> Le Friday 27 June 2008 10:43:06 Alexnb, vous avez écrit :
>> I have never used the urllib or the urllib2. I really have looked online
>> for help on this issue, and mailing lists, but I can't figure out my
>> problem because people haven't been helping me, which is why I am here!
>> :].
>> Okay, so basically I want to be able to submit a word to dictionary.com
>> and
>> then get the definitions. However, to start off learning urllib2, I just
>> want to do a simple google search. Before you get mad, what I have found
>> on
>> urllib2 hasn't helped me. Anyway, How would you go about doing this. No,
>> I
>> did not post the html, but I mean if you want, right click on your
>> browser
>> and hit view source of the google homepage. Basically what I want to know
>> is how to submit the values(the search term) and then search for that
>> value. Heres what I know:
>>
>> import urllib2
>> response = urllib2.urlopen("http://www.google.com/";)
>> html = response.read()
>> print html
>>
>> Now I know that all this does is print the source, but thats about all I
>> know. I know it may be a lot to ask to have someone show/help me, but I
>> really would appreciate it.
> 
> This example is for google, of course using pygoogle is easier in this
> case, 
> but this is a valid example for the general case :
> 
[207]: import urllib, urllib2
> 
> You need to trick the server with an imaginary User-Agent.
> 
[208]: def google_search(terms) :
> return urllib2.urlopen(urllib2.Request("http://www.google.com/search?";
> +  
> urllib.urlencode({'hl':'fr', 'q':terms}),
>headers={'User-Agent':'MyNav
> 1.0 
> (compatible; MSIE 6.0; Linux'})
>   ).read()
>.:
> 
[212]: res = google_search("python & co")
> 
> Now you got the whole html response, you'll have to parse it to recover
> datas, 
> a quick & dirty try on google response page :
> 
[213]: import re
> 
[214]: [ re.sub('<.+?>', '', e) for e in re.findall('.*?', 
> res) ]
> ...[229]:
> ['Python Gallery',
>  'Coffret Monty Python And Co 3 DVD : La Premi\xe8re folie des Monty ...',
>  'Re: os x, panther, python & co: msg#00041',
>  'Re: os x, panther, python & co: msg#00040',
>  'Cardiff Web Site Design, Professional web site design services ...',
>  'Python Properties',
>  'Frees < Programs < Python < Bin-Co',
>  'Torb: an interface between Tcl and CORBA',
>  'Royal Python Morphs',
>  'Python & Co']
> 
> 
> -- 
> _
> 
> Maric Michaud
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://www.nabble.com/using-urllib2-tp18150669p18160312.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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

Re: Hamming Distance

2008-06-27 Thread Jared Grubb
Matimus,
I was surprised that "lazy" was the algorithm that won your time tests, and
I saw a way to improve it even better (algorithm is O(# ones in number)
rather than O(# bits in number))
def lazy2(a, b, bits=32):
x = (a ^ b) & ((1 << bits) - 1)
tot = 0
while x:
tot += 1
x &= x-1
return tot

# times on my system (run a few times just to check for sure)
python -mtimeit -s"from ham import *" "test(lazy)"
1 loops, best of 3: 121 usec per loop

python -mtimeit -s"from ham import *" "test(lazy2)"
1 loops, best of 3: 62.4 usec per loop

Check my math, but I think that's correct. Here's my derivation (but it's
been a while since my Boolean algebra days, so I may've made a mistake!) It
sounds right, though, since subtracting one in two's complement flips the
rightmost one and inverts the zeros to the right of it. So, x & (x-1) would
remove the rightmost one. Right?

Long Derivation: The "trick" to finding the rightmost one in a number:
pos = x ^ (x-1)
It has to do with how two's-complement works. In our algorithm above, we are
trying to count them, so we want to flip off the bits one by one from the
right. So in each loop:
x = x & ~pos
But, then you notice you can simplify it even more (let y=x-1) and use
mult/add syntax for & and | and use X=~x and Y=~y
x * ~(x ^ y)
x * ~(xY+Xy)[ def of ^ ]
x * (~(xY)*~(Xy)) [ DeMoires Law ]
x * ( (X+y)*(x+Y) ) [ inversion]
x * (X+y) * (x+Y)  [ associative]
(xX+xy)*(x+Y)  [ distributive ]
xy*(x+Y)  [ xX = 0 ]
xy+xyY   [ distrib ]
xy[yY = 0]

So,
x &= x-1

On 19 Jun 2008, at 17:37, Matimus wrote:

On Jun 19, 4:27 pm, godavemon <[EMAIL PROTECTED]> wrote:

I need to calculate the Hamming Distance of two integers.  The hamming

distance is the number of bits in two integers that don't match.  I

thought there'd be a function in math or scipy but i haven't been able

to find one.  This is my function but it seems like there should be a

faster way.  I do this computation many times and speed up is

important.


def hamdist( a, b , bits = 32):

def _hamdist( x, bits):

if bits:

return (x & 1) + _hamdist(x >> 1, bits-1)

return x & 1

return _hamdist( a ^ b, bits)


Another alternative would be to convert the XOR to a binary string and

count the # of 1's.


Which would be fastest?  Are there better alternatives?


Thanks!


I see no good reason to use recursion for this type of thing. Here are
some of my attempts:

[code]
from math import log

def yours(a, b , bits = 32):
def _hamdist( x, bits):
if bits:
return (x & 1) + _hamdist(x >> 1, bits-1)
return x & 1
return _hamdist(a ^ b, bits)


def simple(a, b, bits=32):
   x = a ^ b
   return sum((x >> i & 1) for i in xrange(bits))

def lazy(a, b, bits=32):
   x = (a ^ b) & ((1 << bits) - 1)
   tot = 0
   while x:
   tot += x & 1
   x >>= 1
   return tot

def fancy(a, b, bits=32):
   x = (a ^ b) & ((1 << bits) - 1)
   tot = 0
   while x:
   tot += 1
   x ^= 1 << int(log(x, 2))
   return tot

test_vals = (
   ((0x, 0), 32),
   ((0,0), 0),
   ((1,0), 1),
   ((0x8000, 0), 1),
   ((0x, 0), 16)
   )

def test(f):
   test_vals = (
   ((0x, 0), 32), # ALL
   ((0,0), 0), # None
   ((1,0), 1), # First
   ((0x8000, 0), 1), # Last
   ((0x, 0), 16), # Every Other
   ((0x, 0), 16), # First Half
   ((0x, 0), 16), # Last Half
   )
   for i, (args, exp) in enumerate(test_vals):
   if f(*args) != exp:
   return 0
   return 1

if __name__ == "__main__":
   for f in (yours, simple, lazy, fancy):
   if not test(f):
   print "%s failed"%f.__name__
[/code]

The python module `timeit` is handy for testing speed:

python -mtimeit -s"from hamdist import *" "test(yours)"
1 loops, best of 3: 95.1 usec per loop

python -mtimeit -s"from hamdist import *" "test(simple)"
1 loops, best of 3: 65.3 usec per loop

python -mtimeit -s"from hamdist import *" "test(lazy)"
1 loops, best of 3: 59.8 usec per loop

python -mtimeit -s"from hamdist import *" "test(fancy)"
1 loops, best of 3: 77.2 usec per loop

Even the ridiculous `fancy` version beat the recursive version.

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

ImportError: DLL load failed

2008-06-27 Thread Tony May
I'm having trouble importing when I run in Python. The hello world program
passes the test during the bjam build but gives an error about loading the
dll
when I import from a python script.

first the test from running bjam.
...patience...
...found 1915 targets...
...using 1 temp target...
...updating 2 targets...
...using hello_ext.pyd...
capture-output bin\hello.test\msvc-8.0express\debug\threading-multi\hello
1 file(s) copied.
**passed** bin\hello.test\msvc-8.0express\debug\threading-multi\hello.test
...updated 2 targets...

then trying to run the script from python
I copied the pyd file and the rest of the output dir to c:\python25\dlls

C:\Program Files\boost\boost_1_35_0\libs\python\example\tutorial>python
hello.py

Traceback (most recent call last):
  File "hello.py", line 6, in 
import hello_ext
ImportError: DLL load failed: This application has failed to start because
the a
pplication configuration is incorrect. Reinstalling the application may fix
this
 problem.

Thanks for any help

Tony
 Reply

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

Re: Sequence iterators with __index__

2008-06-27 Thread yaipa
On Jun 24, 4:19 pm, schickb <[EMAIL PROTECTED]> wrote:
> On Jun 24, 3:45 pm, Matimus <[EMAIL PROTECTED]> wrote:
>
>
>
> > > I think it would be useful if iterators on sequences had the __index__
> > > method so that they could be used to slice sequences. I was writing a
> > > class and wanted to return a list iterator to callers.  I then wanted
> > > to let callers slice from an iterator's position, but that isn't
> > > supported without creating a custom iterator class.
>
> > Could you post an example of what you are talking about? I'm not
> > getting it.
>
> Interactive mock-up:
>
> >>> a = ['x','y','z']
> >>> it = iter(a)
> >>> a[it:]
> ['x', 'y', 'z']
> >>> it.next()
> 'x'
> >>> a[it:]
> ['y', 'z']
> >>> a[:it]
> ['x']
> >>> it.next()
> 'y'
> >>> a[it:]
>
> ['z']
>
> This lets you use sequence iterators more general position indicators.
> Currently if you want to track a position and slice from a tracked
> position you must do it manually with an integer index. It's not
> difficult, but given that sequence iterators already do that already
> it seems redundant (and of course more error prone).
>
> > In any case, the first step is writing a PEP.http://www.python.org/dev/peps/
>
> Ok thanks, but I do want some idea of interest level before spending a
> bunch of time on this.
>
> -Brad


Brad,

enumerate() seems to solve this problem for me

>>
>> a = ['x','y','z']
>> ea = enumerate(a)
>> index, value = ea.next()
>> index
0
>> value
'x'
>> index, value = ea.next()
>> a[index:]
['y', 'z']
>>

putting this bit of code in a thin class wrapper should be useful to
keep the two data objects in sync. adding a reset() method allows you
to rebuild the enumerate object as often as needed.

Hope this helps.

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


Query regarding PythonQt

2008-06-27 Thread Shankar Narayana
Hi,
 I am newbie to PythonQt. I wanted to access the Qt objects created in C++
using Python and update things. I had a look at this URL "
http://doc.trolltech.com/qq/qq23-pythonqt.html#decoratorsandcwrappers"; which
talks about using PythonQt for the same.
  I followed the instructions given in the example. I created my cpp file
and .py file and could make them working.
  But once after the first time after .pyc file is created, my program no
longer executes. It is giving me a segmentation fault. If I remove my .pyc
file and run the program, things work fine.

My cpp file
#include 
#include 
#include "PythonQt.h"
int main(int argc, char* argv[])
{
QApplication app(argc,argv);
QTextEdit *welcomemsg = new QTextEdit("Hi whatsup");
PythonQt::init();
PythonQtObjectPtr mainModule = PythonQt::self()->getMainModule();
mainModule.addObject("welcomemsg",welcomemsg);  // Check with different
names
mainModule.evalFile("Pyscript.py");
mainModule.removeVariable("welcomemsg");
PythonQt::cleanup();
return app.exec();
}

My Python file  (Pyscript.py)

from PythonQt import *
#append the text to the existing text edit
welcomemsg.append("Hurray I did it")
welcomemsg.show()

Can somebody help me what makes this not to run once Python interpreter
works on the Python file and creates a .pyc file ?


Regards,
Shankar
--
http://mail.python.org/mailman/listinfo/python-list

Re: Cyclic imports

2008-06-27 Thread James
> In code that runs after the module has been imported (basically
> anything defined in a function that isn't called by code that runs at
> module time), you can expect the variables defined in the imported
> module to be available.
>
> If you have circular imports involved, making sure the modules import
> in a certain order can be quite hairy.  (Faced with this problem, I
> found it necessary to write an import hook to pre-import certain
> modules.)

Ok, thanks for all the advice: I now have the class architecture I was
looking for, by using much less specific imports, as Dan originally
suggested.

Re-factoring the use of partially loaded modules into functions wasn't
an option for me, unfortunately, as the classes were being used as
super classes or class variables. So, the code is a bit more verbose
than before, but works!

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


Re: ask for a RE pattern to match TABLE in html

2008-06-27 Thread Dan
On Jun 27, 1:32 pm, "David C. Ullrich" <[EMAIL PROTECTED]> wrote:
> In article
> <[EMAIL PROTECTED]>,
>  Jonathan Gardner <[EMAIL PROTECTED]> wrote:
>
> > On Jun 26, 3:22 pm, MRAB <[EMAIL PROTECTED]> wrote:
> > > Try something like:
>
> > > re.compile(r'.*?', re.DOTALL)
>
> > So you would pick up strings like "foo > td>"? I doubt that is what oyster wants.
>
> I asked a question recently - nobody answered, I think
> because they assumed it was just a rhetorical question:
>
> (i) It's true, isn't it, that it's impossible for the
> formal CS notion of "regular expression" to correctly
> parse nested open/close delimiters?

Yes. For the proof, you want to look at the pumping lemma found in
your favorite Theory of Computation textbook.

>
> (ii) The regexes in languages like Python and Perl include
> features that are not part of the formal CS notion of
> "regular expression". Do they include something that
> does allow parsing nested delimiters properly?

So, I think most of the extensions fall into syntactic sugar
(certainly all the character classes \b \s \w, etc). The ability to
look at input without consuming it is more than syntactic sugar, but
my intuition is that it could be pretty easily modeled by a
nondeterministic finite state machine, which is of equivalent power to
REs. The only thing I can really think of that is completely non-
regular is the \1 \2, etc syntax to match previously match strings
exactly. But since you can't to an arbitrary number of them, I don't
think its actually context free. (I'm not prepared to give a proof
either way). Needless to say that even if you could, it would be
highly impractical to match parentheses using those.

So, yeah, to match arbitrary nested delimiters, you need a real
context free parser.

>
> --
> David C. Ullrich


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


Re: Django or TurboGears for a new project

2008-06-27 Thread Jason Scheirer
On Jun 27, 9:52 am, Kirk Strauser <[EMAIL PROTECTED]> wrote:
> We're looking to migrate a Zope site to Django, but before getting beyond
> the dreaming stage, I thought I'd see what others are doing these days.
>
> If you were going to start a fairly complex site today with lots of DB
> integration, would you begin with Django or TurboGears, or something else
> entirely?
>
> I'm more interested in social, rather than technical reasons (unless there's
> something you absolutely love or despise about one or the other).
> Popularity is actually a pretty big consideration because I'd like to work
> with an eager community who's doing cool new things.
>
> I know asking for comparisons like this is potentially flamebait-ish, but I
> really don't mean it that way.  It's just that I don't have a lot of friends
> in the industry in this particular development niche who I can ask for
> recommendations, and this seems like as good a place as any to find subject
> matter experts.
>
> Thanks,
> --
> Kirk Strauser
> The Day Companies

I've noticed I write a lot less code with TurboGears (as in my apps
are done faster and smaller), but you're going to find more Django
programmers and therefore a larger developer force and more recipes
online.
--
http://mail.python.org/mailman/listinfo/python-list


[Employment] New TurboGears Job in Eugene, OR

2008-06-27 Thread Silas Snider
I've been heading up a team writing a rather large TurboGears app and
I've had
to leave, so we're looking for replacements. The description is below.

-
Full position announcement at: 

In an eggshell:

Python/Turbogears Web Applications Programmer
Full-time academic year position
Salary range: $2819 - $4404 per month ( $16.26 - $25.41 per hour)

Work location: EC CARES Building, University of Oregon, 299 E 18th
Ave, Eugene OR

Early Intervention (EI) and Early Childhood Special Education (ECSE)
are state and federally funded programs that provide services for
children with developmental delays. All counties in Oregon have EI/
ECSE programs, and most use case management and forms processing
software developed at EC CARES (the EI/ECSE provider for Lane County).
This is a new position responsible for the technical design and
programming of this software, and works closely with the project
manager who provides oversight and handles implementation and user
support.

The software includes case management features, forms subsystem,
immunization analysis, medicaid billing record management and
reporting tools. It is developed on Macintosh hardware and hosted on
Mac OSX Server, and designed for Firefox (any platform). The project
uses mostly open source software, and specifically these applications
and frameworks:

Turbogears
Python 2.5
SQLObject
MySQL
OpenOffice.org
Prototype
PyYaml
Scriptaculous
XML
CSS
XHTML
Subversion
Mac OSX Server Tools

The following knowledge, skills and experience are necessary for this
position:

Expert Python and SQL programming skills, and proficiency with
Javascript, CSS, XHTML and web standards. Professional experience with
open source projects, ideally using Turbogears and MySQL. Experience
with Mac OSX Server or other server administration. Familiarity with
version control. Skills using on-line documentation for open source
packages. Wide knowledge of open-source software and ability to find,
evaluate, learn and implement new open source technologies.

If any questions about the position, please contact:

Dan Smellow
ECData admin
541.346.0819
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >