Re: is decorator the right thing to use?

2008-09-24 Thread Diez B. Roggisch

Dmitry S. Makovey schrieb:

Dmitry S. Makovey wrote:

In my real-life case A is a proxy to B, C and D instances/objects, not
just one. 


forgot to mention that above would mean that I need to have more than one
decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter
about which property of A has instance of which class etc. 


Unless I'm totally "out for lunch" and there are better ways of implementing
this (other than copy-pasting stuff whenever anything in B, C or D
changes).


__getattr__?

class Proxy(object):


def __init__(self, delegate):
self._delegate = delegate


def __getattr__(self, attr):
v = getattr(self._delegate, attr)
if callable(v):
   class CallInterceptor(object):
 def __init__(self, f):
 self._f = f

 def __call__(self, *args, **kwargs):
 print "Called " + str(self._f) + " with " + 
str(args) + str(kwargs)

 return self._f(*args, **kwargs)
   return CallInterceptor(v)
return v


Decorators have *nothing* to do with this. They are syntactic sugar for


def foo(...):
...

foo = a_decorator(foo)

Nothing less, nothing more.

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


Re: curses.setsyx()?

2008-09-24 Thread Tim Roberts
[EMAIL PROTECTED] wrote:

>On Sep 23, 4:16 pm, [EMAIL PROTECTED] wrote:
>> On Sep 22, 11:24 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
>> > [EMAIL PROTECTED] wrote:
>> > >On Sep 19, 6:42 pm, [EMAIL PROTECTED] wrote:
>> > >> On Sep 19, 1:24 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
>>
>> > >> > [EMAIL PROTECTED] wrote:
>>
>> > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the 
>> > >> > >curses
>> > >> > >cursor. Any alternatives/solutions?
>>...
>> > >> I added it and it still doesn't work. This is what I'm doing when I
>> > >> want to display the cursor and prepare it for input at 2,3:
>>
>> > >> curses.echo()
>> > >> curses.curs_set(1)
>> > >> curses.setsyx(2,3)
>> > >> curses.doupdate()
>>
>> > >Any idea what's wrong?
>>
>> http://pastebin.com/m6413db1
>>
>> Run that and press 'n' key. It is supposed to move the cursor to 2,3
>> and it doesn't.

Of course it does.  It moves the cursor, then does an update, then
immediately calls draw.game, which redraws the screen and moves the cursor.
If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to
leave the cursor somewhere, you can't draw more text afterward.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Time.sleep(0.0125) not available within Linux

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote:

> Just a thought, your minimum sleep time is probably limited by the
> resolution of the system "HZ" clock. Type
> 
> less /proc/config.gz


$ less /proc/config.gz
/proc/config.gz: No such file or directory


What OS are you using?



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


Re: Off topic: Sent from my Foo messages

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 20:04:14 -0700, Sean DiZazzo wrote:

>> --
>> Steven
> 
> I don't appreciate the two lines you put above your name in your posts. 
> Please remove them in the future.

I don't like them either, but it is an email and Usenet standard to 
separate the body of your post from the signature with "-- ". I'm afraid 
that as obnoxious as the dashes are, leaving them out would be much worse.



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


Re: How to parse a string completely into a list

2008-09-24 Thread john . ford
On Sep 24, 10:12 pm, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Sep 24, 9:44 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> >> On Wed, Sep 24, 2008 at 8:30 PM,  <[EMAIL PROTECTED]> wrote:
> >>> I want to take a long alpha-numeric string with \n and white-space and
> >>> place ALL elements of the string (even individual parts of a long
> >>> white-space) into separate list elements. The most common way I've
> >>> seen this performed is with the split() function, however I don't
> >>> believe that it has the power to do what I am looking for.
> >>> Any suggestions?
> >>> thanks
> >> Could you please define exactly what you mean by "elements" of a string?
>
> >> If you mean characters, then just use list():>>> list("  \n \t abc")
>
> >> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']
>
> >> Regards,
> >> Chris
>
> > Worked like a charm.
> > kudos!
>
> Why do you need to convert it to a list? Strings are sequences, so you
> can do things like slice them or iterate through them by character:
>
> >>> for character in "foo":
>
> ...     print character
> ...
> f
> o
> o
>
> --

The string draws a map that I then want to be able to traverse
through. If I can count through the individual characters of a list I
can create an x-y coordinate plane for navigation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple processes with private working dirs

2008-09-24 Thread alex23
On Sep 25, 3:37 am, "Tim Arnold" <[EMAIL PROTECTED]> wrote:
> Am I missing something?

Do you mean something other than the replies you got the last time you
asked the exact same question?

http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c13cbb84f88f2b
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parse a string completely into a list

2008-09-24 Thread Matt Nordhoff
[EMAIL PROTECTED] wrote:
> On Sep 24, 9:44 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
>> On Wed, Sep 24, 2008 at 8:30 PM,  <[EMAIL PROTECTED]> wrote:
>>> I want to take a long alpha-numeric string with \n and white-space and
>>> place ALL elements of the string (even individual parts of a long
>>> white-space) into separate list elements. The most common way I've
>>> seen this performed is with the split() function, however I don't
>>> believe that it has the power to do what I am looking for.
>>> Any suggestions?
>>> thanks
>> Could you please define exactly what you mean by "elements" of a string?
>>
>> If you mean characters, then just use list():>>> list("  \n \t abc")
>>
>> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']
>>
>> Regards,
>> Chris
> 
> Worked like a charm.
> kudos!

Why do you need to convert it to a list? Strings are sequences, so you
can do things like slice them or iterate through them by character:

>>> for character in "foo":
... print character
...
f
o
o
>>>
-- 
--
http://mail.python.org/mailman/listinfo/python-list


multiple processes with private working dirs

2008-09-24 Thread Tim Arnold
I have a bunch of processes to run and each one needs its own working 
directory. I'd also like to know when all of the processes are finished.

(1) First thought was threads, until I saw that os.chdir was process-global.
(2) Next thought was fork, but I don't know how to signal when each child is 
finished.
(3) Current thought is to break the process from a method into a external 
script; call the script in separate threads.  This is the only way I can see 
to give each process a separate dir (external process fixes that), and I can 
find out when each process is finished (thread fixes that).

Am I missing something? Is there a better way? I hate to rewrite this method 
as a script since I've got a lot of object metadata that I'll have to 
regenerate with each call of the script.

thanks for any suggestions,
--Tim Arnold


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


The Python computer language

2008-09-24 Thread ROSEEE
http://pythoncomputer.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to parse a string completely into a list

2008-09-24 Thread john . ford
On Sep 24, 9:44 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> On Wed, Sep 24, 2008 at 8:30 PM,  <[EMAIL PROTECTED]> wrote:
> > I want to take a long alpha-numeric string with \n and white-space and
> > place ALL elements of the string (even individual parts of a long
> > white-space) into separate list elements. The most common way I've
> > seen this performed is with the split() function, however I don't
> > believe that it has the power to do what I am looking for.
> > Any suggestions?
> > thanks
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Could you please define exactly what you mean by "elements" of a string?
>
> If you mean characters, then just use list():>>> list("  \n \t abc")
>
> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']
>
> Regards,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

Worked like a charm.
kudos!
--
http://mail.python.org/mailman/listinfo/python-list


Re: is decorator the right thing to use?

2008-09-24 Thread Dmitry S. Makovey
Dmitry S. Makovey wrote:
> In my real-life case A is a proxy to B, C and D instances/objects, not
> just one. 

forgot to mention that above would mean that I need to have more than one
decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter
about which property of A has instance of which class etc. 

Unless I'm totally "out for lunch" and there are better ways of implementing
this (other than copy-pasting stuff whenever anything in B, C or D
changes).
--
http://mail.python.org/mailman/listinfo/python-list


Re: is decorator the right thing to use?

2008-09-24 Thread Dmitry S. Makovey
Aaron "Castironpi" Brady wrote:
 
> It might help to tell us the order of events that you want in your
> program.  You're not using 'mymethod' or 'mymethod2', and you probably
> want 'return fnew' for the future.  Something dynamic with __getattr__
> might work.  Any method call to A, that is an A instance, tries to
> look up a method of the same name in the B instance it was initialized
> with.

well 'mymethod' and 'mymethod2' were there just to show that A doesn't
function as a pure proxy - it has methods of it's own. See my respnse to
Steve - I proxy messages to more than one aggregated object. going over
them on __getattr__ to look up methods just doesn't seem to be really
efficient to me (I might be wrong though). Decorators seemed to present
good opportunity to simplify the code (well except for the decorator
function itself :) ), make code bit more "fool-proofed" (and give me the
opportunity to test decorators in real life, he-he).

So decorators inside of B just identify that those methods will be proxied
by A. On one hand from logical standpoint it's kind of weird to tell class
that it is going to be proxied by another class, but declaration would be
real close to original function definition which helps to identify where is
it used.

Note that my decorator doesn't change original function - it's a subversion
of decorator to a certain degree as I'm just hooking into python machinery
to add methods to A upon their declaration in B (or so I think).


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


Re: How to parse a string completely into a list

2008-09-24 Thread Chris Rebert
On Wed, Sep 24, 2008 at 8:30 PM,  <[EMAIL PROTECTED]> wrote:
> I want to take a long alpha-numeric string with \n and white-space and
> place ALL elements of the string (even individual parts of a long
> white-space) into separate list elements. The most common way I've
> seen this performed is with the split() function, however I don't
> believe that it has the power to do what I am looking for.
> Any suggestions?
> thanks
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Could you please define exactly what you mean by "elements" of a string?

If you mean characters, then just use list():
>>> list("  \n \t abc")
[' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c']

Regards,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Off topic: Sent from my Foo messages

2008-09-24 Thread Terry Reedy

Steven D'Aprano wrote:
I'm seeing more and more posts from various people, on this list and 
others, with statements like the following:


On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote:


Sent from my iPhone


Also "Sent from my Blackberry" and similar.

Without wishing to be rude to David, who I'm sure is a nice guy and not 
at all the pretentious git that such a line makes him appear, are people 
adding this comment to the bottom of their posts, or is it something that 
their device automatically appends to the post?


If people are adding it themselves, that's nice, I'm sure you're really 
excited about your new toy, but the rest of us don't care a monkey's 
toss. And if the device is automatically appending it, I think that's 
pretty damn rude and a good reason to avoid buying the obnoxious machines.


At least it is just one tag line and the the 20 lines of legal 'If you 
received this in error' spam some  organizations tack on the end ;-).


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


Re: is decorator the right thing to use?

2008-09-24 Thread Dmitry S. Makovey
[EMAIL PROTECTED] wrote:
> Your code below is very abstract, so it's kind of hard to figure out
> what problem you're trying to solve, but it seems to me that you're
> using the B proxy class to decorate the A target class, which means
> you want one of these options:

Sorry for unclarities in original post. Basically A aggregates object of
class B (example with no decorators and again it's oversimplified):

class A:
b=None
def __init__(self,b):
self.b=b

def amethod(self,a):
print "A::amethod ", a

def bmethod(self,a):
print "A::bmethod ",a
return self.b.bmethod(a)

def bmethod2(self,a,z):
print "A::bmethod2 ",a,z
return self.b.bmethod2(a,z)


class B:
def __init__(self):
self.val=a

def bmethod(self,a):
print "B::bmethod ",a

def bmethod2(self,a,z):
print "B::bmethod2 ",a,z


b=B()
a=A(b)
a.bmethod('foo')
a.bmethod2('bar','baz')

In my real-life case A is a proxy to B, C and D instances/objects, not just
one. If you look at above code - whenever I write new method in either B, C
or D I have to modify A, or even when I modify signature (say, add
parameter x to bmethod) in B, C or D I have to make sure A is synchronized.
I was hoping to use decorator to do it automatically for me. Since the
resulting code is virtually all the same for all those proxy methods it
seems to be a good place for automation. Or am I wrong assuming that?
(since it is my first time using decorators I honestly don't know)

Abovementioned code ilustrates what I am doing right now. My original post
is an attempt to make things more automated/foolproof.

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


Re: Schwartzian transform for tuple in list

2008-09-24 Thread Terry Reedy

David Di Biase wrote:
When you say slightly, is it enough to make a difference? Why would 
getitems be faster even - not sure I can think why...




Using key is faster than cmp because key is called just once for each 
item whereas cmp is called once for each of the O(nlogn) compares.


Operator.itemgetter is written in C and hence should be faster than a 
wrapper written in Python.


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


Re: is decorator the right thing to use?

2008-09-24 Thread Aaron "Castironpi" Brady
On Sep 24, 5:21 pm, "Dmitry S. Makovey" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> after hearing a lot about decorators and never actually using one I have
> decided to give it a try. My particular usecase is that I have class that
> acts as a proxy to other classes (i.e. passes messages along to those
> classes) however hand-coding this type of class is rather tedious, so I
> decided to use decorator for that. Can somebody tell me if what I'm doing
> is a potential shot-in-the-foot or am I on the right track? (Note, It's
> rather rudimentary proof-of-concept implementation and not the final
> solution I'm about to employ so there are no optimizations or
> signature-preserving code there yet, just the idea).
>
> Here's the code:
>
> class A:
>     b=None
>     def __init__(self,b):
>         self.val='aval'
>         self.b=b
>         b.val='aval'
>
>     def mymethod(self,a):
>         print "A::mymethod, ",a
>
>     def mymethod2(self,a):
>         print "A::another method, ",a
>
> def Aproxy(fn):
>     def delegate(*args,**kw):
>         print "%s::%s" % (args[0].__class__.__name__,fn.__name__)
>         args=list(args)
>         b=getattr(args[0],'b')
>         fnew=getattr(b,fn.__name__)
>         # get rid of original object reference
>         del args[0]
>         fnew(*args,**kw)
>     setattr(A,fn.__name__,delegate)
>     return fn
>
> class B:
>     def __init__(self):
>         self.val='bval'
>
>     @Aproxy
>     def bmethod(self,a):
>         print "B::bmethod"
>         print a, self.val
>
>     @Aproxy
>     def bmethod2(self,a):
>         print "B::bmethod2"
>         print a, self.val
>
> b=B()
> b.bmethod('foo')
> a=A(b)
> b=B()
> b.val='newval'
> a.bmethod('bar')
> a.bmethod2('zam')

It might help to tell us the order of events that you want in your
program.  You're not using 'mymethod' or 'mymethod2', and you probably
want 'return fnew' for the future.  Something dynamic with __getattr__
might work.  Any method call to A, that is an A instance, tries to
look up a method of the same name in the B instance it was initialized
with.

a.foo( ) -> 'in a.foo' -> 'calling b.foo' -> 'return' -> 'return'
a.mymethod( ) -> 'in a.mymethod' -> 'calling b.mymethod' ->
AttributeError: 'b' has no attribute 'mymethod'.
--
http://mail.python.org/mailman/listinfo/python-list


How to parse a string completely into a list

2008-09-24 Thread john . ford
I want to take a long alpha-numeric string with \n and white-space and
place ALL elements of the string (even individual parts of a long
white-space) into separate list elements. The most common way I've
seen this performed is with the split() function, however I don't
believe that it has the power to do what I am looking for.
Any suggestions?
thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple processes, private working directories

2008-09-24 Thread Carl Banks
On Sep 24, 9:27 pm, Tim Arnold <[EMAIL PROTECTED]> wrote:
> (2) Next thought was fork, but I don't know how to signal when each
> child is
> finished.

Consider the multiprocessing module, which is available in Python 2.6,
but it began its life as a third-party module that acts like threading
module but uses processes.  I think you can still run it as a third-
party module in 2.5.


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


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Aaron "Castironpi" Brady
On Sep 24, 9:49 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady"
>
> <[EMAIL PROTECTED]> wrote:
> > On Sep 24, 8:40 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> > > ... I think
> > > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
> > > all variables for placeholders in the tuple, is better. It's certainly
> > > more readible.
>
> > It's a different answer if you have 'things is/are'.  '%d thing%s %s'%
> > ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ).  Or excluding
> > prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's
> > are' if i!= 1 else ' is' ).
>
> Forgive me for being dull, my caffeine levels have not yet optimal,
> but I don't follow.  Both the solutions you propose do put all the
> placeholder variables in the tuple.  Or are you saying it no longer
> remains readible?
>
> BTW you repeated my mistake with the first scraplet of code.

Ah yes.  Maybe the order of precedence can undergo a change in the
future.  ... Though talk about backwards incompatible.  They were two
options if you have a verb with your noun, which would need a
conditional too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple processes, private working directories

2008-09-24 Thread Karthik Gurusamy
On Sep 24, 6:27 pm, Tim Arnold <[EMAIL PROTECTED]> wrote:
> I have a bunch of processes to run and each one needs its own working
> directory. I'd also like to know when all of the processes are
> finished.
>
> (1) First thought was threads, until I saw that os.chdir was process-
> global.
> (2) Next thought was fork, but I don't know how to signal when each
> child is
> finished.
> (3) Current thought is to break the process from a method into a
> external
> script; call the script in separate threads.  This is the only way I
> can see
> to give each process a separate dir (external process fixes that), and
> I can
> find out when each process is finished (thread fixes that).
>
> Am I missing something? Is there a better way? I hate to rewrite this
> method
> as a script since I've got a lot of object metadata that I'll have to
> regenerate with each call of the script.

Use subprocess; it supports a cwd argument to provide the given
directory as the child's working directory.

Help on class Popen in module subprocess:

class Popen(__builtin__.object)
 |  Methods defined here:
 |
 |  __del__(self)
 |
 |  __init__(self, args, bufsize=0, executable=None, stdin=None,
stdout=None, st
derr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None,
env=None, un
iversal_newlines=False, startupinfo=None, creationflags=0)
 |  Create new Popen instance.

You want to provide the cwd argument above.
Then once you have launched all your n processes, run thru' a loop
waiting for each one to finish.

# cmds is a list of dicts providing details on what processes to run..
what it's cwd should be

runs = []
for c in cmds:
  run =  subprocess.Popen(cmds['cmd'], cwd = cmds['cwd'] . etc
other args)
  runs.append(run)

# Now wait for all the processes to finish
for run in runs:
  run.wait()

Note that if any of the processes generate lot of stdout/stderr, you
will get a deadlock in the above loop. Then you way want to go for
threads or use run.poll and do the reading of the output from your
child processes.

Karthik


>
> thanks for any suggestions,
> --Tim Arnold

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


Re: Off topic: Sent from my Foo messages

2008-09-24 Thread Sean DiZazzo


> --
> Steven

I don't appreciate the two lines you put above your name in your
posts.  Please remove them in the future.

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


Re: Off topic: Sent from my Foo messages

2008-09-24 Thread Chris Rebert
On Wed, Sep 24, 2008 at 7:38 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> I'm seeing more and more posts from various people, on this list and
> others, with statements like the following:
>
> On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote:
>
>> Sent from my iPhone
>
> Also "Sent from my Blackberry" and similar.
>
> Without wishing to be rude to David, who I'm sure is a nice guy and not
> at all the pretentious git that such a line makes him appear, are people
> adding this comment to the bottom of their posts, or is it something that
> their device automatically appends to the post?

It's on by default for the iPhone/iTouch but there's a setting to
change the signature (including to nothing). Don't know about the
Blackberry.

>
> If people are adding it themselves, that's nice, I'm sure you're really
> excited about your new toy, but the rest of us don't care a monkey's
> toss. And if the device is automatically appending it, I think that's
> pretty damn rude and a good reason to avoid buying the obnoxious machines.

Eh, that's a bit extreme; though I admit it can sometimes be annoying
(but not very much).

Regards,
Chris

Sent using a Computer, the Internet, Gmail, Firefox, unix, glibc, ...
;P

>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 24, 8:40 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> > ... I think
> > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
> > all variables for placeholders in the tuple, is better. It's certainly
> > more readible.
>
> It's a different answer if you have 'things is/are'.  '%d thing%s %s'%
> ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ).  Or excluding
> prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's
> are' if i!= 1 else ' is' ).

Forgive me for being dull, my caffeine levels have not yet optimal,
but I don't follow.  Both the solutions you propose do put all the
placeholder variables in the tuple.  Or are you saying it no longer
remains readible?

BTW you repeated my mistake with the first scraplet of code.

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


Off topic: Sent from my Foo messages

2008-09-24 Thread Steven D'Aprano
I'm seeing more and more posts from various people, on this list and 
others, with statements like the following:

On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote:

> Sent from my iPhone

Also "Sent from my Blackberry" and similar.

Without wishing to be rude to David, who I'm sure is a nice guy and not 
at all the pretentious git that such a line makes him appear, are people 
adding this comment to the bottom of their posts, or is it something that 
their device automatically appends to the post?

If people are adding it themselves, that's nice, I'm sure you're really 
excited about your new toy, but the rest of us don't care a monkey's 
toss. And if the device is automatically appending it, I think that's 
pretty damn rude and a good reason to avoid buying the obnoxious machines.



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


Re: Comparing float and decimal

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 04:30:03 -0500, Nick Craig-Wood wrote:


> Both the Fraction module and the Decimal module could represent floats
> exactly and reversibly since floats are of the form
> 
>   mantissa * 2**exponent
> 
> which is exactly representable as a fraction (rational) and also as
> 
>   mantissa2 * 10**exponent2
> 
> as to why we don't do this...
> 
> I guess it is to preserve the sanity of the user when they write
> fraction(0.1) or decimal(0.1) did they really mean fraction(1,10),
> decimal("0.1") or the exact representations which are
> decimal("0.155511151231257827021181583404541015625") and
> fraction(3602879701896397,2**55)


I would say that in practice the chances that somebody *actually* wanted 
0.155511151231257827021181583404541015625 when they wrote 
0.1 is about the same as the chances that the BDFL will support braces in 
Python 3.0.

(Hint: "from __future__ import braces")


> Given that we let the exact representations leak out anyway (which
> causes a lot of FAQs in this list), eg
> 
 0.1
> 0.10001
> 
> IMHO We should put the exact conversions in for floats to Decimal and
> Fraction by default and add a new section to the FAQ!


But of the reasons for having the Decimal module is to avoid such leaky 
abstractions. Without Decimal (or fraction) there's no obvious way to get 
0.1 exactly. It seems perverse to suggest that by default Decimal should 
deliberately expose the same leaky abstraction that causes so much 
trouble when people use floats.

> In that way people will see floats for what they really are - a crude
> approximation to a rational number ;-)

You can already see that just by printing a float:

>>> 0.3
0.2
>>> 0.1
0.10001


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


Re: urllib error on urlopen

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote:

> Hi,
> 
> I have been using the following code for over a year in one of my
> programs:
> 
> f = urllib2.urlopen('https://www.companywebsite.com/somestring')
> 
> It worked great until the middle of the afternoon yesterday. Now I get
> the following traceback:
...
> URLError:  routines:SSL23_GET_SERVER_HELLO:unknown protocol')>

Have you recently set a proxy where Python can auto-detect it? I 
understand that urllib2 doesn't work well with https proxies.

If so, you can instruct urllib2 not to use a proxy-handler, but it's more 
work. What I do is construct an opener without a proxyhandler:


# untested...
no_proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(no_proxy_support)
f = opener.open('https://www.companywebsite.com/somestring')


If that doesn't work, you may need to build a Request object from the URL 
before passing it to opener.open.



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


Re: Making small executive file for distribution

2008-09-24 Thread Grant Edwards
On 2008-09-25, Larry Bates <[EMAIL PROTECTED]> wrote:
> Marin Brkic wrote:
>> Not commercial distribution, but an academic kind of sorts - giving
>> the exe file to coleagues, so they can use it in their work. Giving
>> .py file is not an option, since due to centralized computer
>> maintenance, they don't (and cannot) have installed python (except the
>> ones that bring their own computer at work, but those are an
>> exception).
>> 
>> As far as I know py2exe is the only option which can do such a thing
>> (make exe files from scripts). Is there a way to make those exe files
>> a little smaller (for a small script they easily go up to 5-10 mb).

> Times have changed, 5-10Mb is REALLY small.  Flash drives hold 4000-8000Mb
> for less than $20 and standard hard drives are now 500Gb.  IMHO you are 
> concerned about a problem that doesn't actually exist.

But what if he wants to distribute his program on a floppy
disk? ;)

[I think only 1 of my 5 machines has a floppy drive, and the
last time I tried to use it, it didn't work.  I did have a
usb-floppy drive somewhere, but I think somebody borrowed it a
couple years ago and never returned it.]

-- 
Grant

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


Re: empty csv file attachments

2008-09-24 Thread Sean DiZazzo
On Sep 24, 1:17 pm, Bobby Roberts <[EMAIL PROTECTED]> wrote:
> hi group.
>
> I'm new to python but a veteran at programming.  This one has me
> stumped.  I have a simple contact form which the user fills out.  The
> email is sent to the site user as well and it is delivered with the
> content in the body of the email as well in nice order.  I have
> modified my code to also send the content as a csv attachment.  On the
> server, the file is perfectly generated with content.  The attachment,
> however, is completely blank.  Any ideas what that could be?  My code
> snippet is shown below:
>
>       if int(attachmenttype)==2 or int(attachmenttype)==3:
>         for field in ctx.request.field_names():
>           if field=='last_name':
>             myfilename=ctx.request.field_value(field)+'.txt'
>         if myfilename=='':
>           myfilename='tempfile.txt'
>         mypath= mynewfilepath + '/' + myfilename
>         f=open(mypath, 'w')
>         mynewstring=''
>         counter=0
>         for field in ctx.request.field_names():
>           if field != 'inquiry_required':
>             mynewstring=mynewstring + field +','
>         if mynewstring[-1]==',':
>           mynewstring=mynewstring[0:len(mynewstring)-1]
>         f.write(mynewstring)
>         f.write ('\n')
>
>         mynewstring=''
>         counter=1
>         for field in ctx.request.field_names():
>           fielddata=ctx.request.field_value(field)
>           if counter==1:
>             dummydata=0
>           else:
>             mynewstring=mynewstring + '"' + fielddata.replace('"','')
> + '",'
>           counter = counter + 1
>         if mynewstring[-1]==',':
>           mynewstring=mynewstring[0:len(mynewstring)-1]
>         f.write(mynewstring)
>         f.write('\n')
>         f.close
>         attachments.append('/'.join((ctx.request.library,
> myfilename)))
>
>  [snip... sends email just after this]
>
> any ideas?

I would sprinkle some print statements in there to narrow it down...

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


Re: Making small executive file for distribution

2008-09-24 Thread Larry Bates

Marin Brkic wrote:

Not commercial distribution, but an academic kind of sorts - giving
the exe file to coleagues, so they can use it in their work. Giving
.py file is not an option, since due to centralized computer
maintenance, they don't (and cannot) have installed python (except the
ones that bring their own computer at work, but those are an
exception).

As far as I know py2exe is the only option which can do such a thing
(make exe files from scripts). Is there a way to make those exe files
a little smaller (for a small script they easily go up to 5-10 mb).

Has anyone had a situation like this ? All your inputs and suggestions
are more then welcomed.

--
Marin



Times have changed, 5-10Mb is REALLY small.  Flash drives hold 4000-8000Mb
for less than $20 and standard hard drives are now 500Gb.  IMHO you are 
concerned about a problem that doesn't actually exist.


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


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote:

> Plenty of people were quick to say that the exception should be passed
> through to the caller.  No one said this behaviour should be documented.
>  There may be little practical difference bewteen calling sys.exit()
> after printing an error and progating an exception if no one using the
> library knows that it could generate that exception in those
> circumstances.

That's true, I didn't explicitly say that the library should be 
documented. Nor did I say that it shouldn't be riddled with bugs. There's 
little practical difference between a buggy library and one that raises 
unexpected (i.e. undocumented) exceptions either.



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


Re: Linq to Python

2008-09-24 Thread r0g
Duncan Booth wrote:
> r0g <[EMAIL PROTECTED]> wrote:
> 
>> OK so maybe I'm being naive here but it looks to me like this new
>> paradigm's big idea is to use a python + SQL type syntax to access data
>> in random objects. Big whoop. It's not that difficult to write a
>> generators that wraps XML files and databases is it?
>>
>> What am I missing here?
> 
> Simple LINQ expressions like the one you gave map easily to Python list 
> comprehensions. What Microsoft have done though is provide a consistent 
> implementation which allows you to write complex SQL like expressions which 
> will work identically on databases or most other sequence types.

Hmm, that's a nice idea in theory but I don't think it's the python
killer Mr/Ms bearophile thinks it is. I can't think of any use cases
where this would save me a great deal of time (certainly not enough to
offset the relative slowness of working in C#) but supposing they do
exist this stuff definitely belongs in a module. Seems to me C# is
playing catchup in most ways and this nugget of 'innovation' is just the
exception that proves the rule.

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


Re: is decorator the right thing to use?

2008-09-24 Thread [EMAIL PROTECTED]
On Sep 24, 3:21 pm, "Dmitry S. Makovey" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> after hearing a lot about decorators and never actually using one I have
> decided to give it a try. My particular usecase is that I have class that
> acts as a proxy to other classes (i.e. passes messages along to those
> classes) however hand-coding this type of class is rather tedious, so I
> decided to use decorator for that. Can somebody tell me if what I'm doing
> is a potential shot-in-the-foot or am I on the right track? (Note, It's
> rather rudimentary proof-of-concept implementation and not the final
> solution I'm about to employ so there are no optimizations or
> signature-preserving code there yet, just the idea).
>

Your code below is very abstract, so it's kind of hard to figure out
what problem you're trying to solve, but it seems to me that you're
using the B proxy class to decorate the A target class, which means
you want one of these options:

  1) Put decorators over the methods in A, not B.  Isn't it the
methods of A that are being decorated here?

  2) Eliminate the decorator syntax and make your code more
expressive:

 a = SomeClass()
 # first call it directly
 x = a.foo()
 y = a.bar()
 # now decorate it
 debug_proxy =
ClassThatDecoratesMethodCallsToObjectWithDebuggingCode(a)
 debug_proxy.decorate_methods('foo', 'bar')

The decorate_methods method would be magical, in terms of overwriting
a's innards, while still preserving the same interface for its users.

But again, I'm just guessing here, because it's hard to know what
problem you're really solving.

Cheers,

Steve

Code quoted below:
> Here's the code:
>
> class A:
>     b=None
>     def __init__(self,b):
>         self.val='aval'
>         self.b=b
>         b.val='aval'
>
>     def mymethod(self,a):
>         print "A::mymethod, ",a
>
>     def mymethod2(self,a):
>         print "A::another method, ",a
>
> def Aproxy(fn):
>     def delegate(*args,**kw):
>         print "%s::%s" % (args[0].__class__.__name__,fn.__name__)
>         args=list(args)
>         b=getattr(args[0],'b')
>         fnew=getattr(b,fn.__name__)
>         # get rid of original object reference
>         del args[0]
>         fnew(*args,**kw)
>     setattr(A,fn.__name__,delegate)
>     return fn
>
> class B:
>     def __init__(self):
>         self.val='bval'
>
>     @Aproxy
>     def bmethod(self,a):
>         print "B::bmethod"
>         print a, self.val
>
>     @Aproxy
>     def bmethod2(self,a):
>         print "B::bmethod2"
>         print a, self.val
>
> b=B()
> b.bmethod('foo')
> a=A(b)
> b=B()
> b.val='newval'
> a.bmethod('bar')
> a.bmethod2('zam')

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


Re: multiple processes, private working directories

2008-09-24 Thread Michael Palmer
On Sep 24, 9:27 pm, Tim Arnold <[EMAIL PROTECTED]> wrote:
> I have a bunch of processes to run and each one needs its own working
> directory. I'd also like to know when all of the processes are
> finished.
>
> (1) First thought was threads, until I saw that os.chdir was process-
> global.
> (2) Next thought was fork, but I don't know how to signal when each
> child is
> finished.
> (3) Current thought is to break the process from a method into a
> external
> script; call the script in separate threads.  This is the only way I
> can see
> to give each process a separate dir (external process fixes that), and
> I can
> find out when each process is finished (thread fixes that).
>
> Am I missing something? Is there a better way? I hate to rewrite this
> method
> as a script since I've got a lot of object metadata that I'll have to
> regenerate with each call of the script.
>
> thanks for any suggestions,
> --Tim Arnold

1, Does the work in the different directories really have to be done
concurrently? You say you'd like to know when each thread/process was
finished, suggesting that they are not server processes but rather
accomplish some limited task.

2. If the answer to 1. is yes: All that os.chdir gives you is an
implicit global variable. Is that convenience really worth a multi-
process architecture? Would it not be easier to just work with
explicit path names instead? You could store the path of the per-
thread working directory in an instance of threading.local - for
example:

>>> import threading
>>> t = threading.local()
>>>
>>> class Worker(threading.Thread):
... def __init__(self, path):
... t.path=path
...

the thread-specific value of t.path would then be available to all
classes and functions running within that thread.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Steven D'Aprano
On Wed, 24 Sep 2008 10:54:40 -0500, Grant Edwards wrote:

> You're right.  I had forgotten that sys.exit() is actually raising the
> system exit exception, and that the application calling the library
> could handle that exception.

Could but shouldn't.

The exception hierarchy was re-designed in Python 2.5 specifically so 
that SystemExit and KeyboardInterrupt no longer inherit from Exception. 
That means this will do the right thing:

try:
process(record)
if changed:
update(record)
except Exception:
# don't write the record if any error occurs
pass


Neither SystemExit nor KeyboardInterrupt are errors, and they should not 
be treated as errors. I quote from the Fine Manual:

[SystemExit] inherits from BaseException instead of StandardError or 
Exception so that it is not accidentally caught by code that catches 
Exception. This allows the exception to properly propagate up and cause 
the interpreter to exit.

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

SystemExit is not an error. KeyboardInterrupt is not an error. Libraries 
should not use SystemExit to signal an error any more than they should 
use MemoryError to signal a missing attribute.

Whether or not an application exits is up to the application to decide, 
not the library it wraps. Libraries should report errors by raising an 
Exception (note the capital E), and the application should decide whether 
or not it is recoverable, and if not, exit (perhaps by simply not 
catching the exception).



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


Re: multiple processes, private working directories

2008-09-24 Thread Cameron Simpson
On 24Sep2008 18:27, Tim Arnold <[EMAIL PROTECTED]> wrote:
| I have a bunch of processes to run and each one needs its own working
| directory. I'd also like to know when all of the processes are
| finished.
| 
| (1) First thought was threads, until I saw that os.chdir was process-
| global.

Yep. But do you need separate working directories?
As opposed to having the thread state include a notional working
directory and constructing file paths within it.

| (2) Next thought was fork, but I don't know how to signal when each
| child is finished.

Open a pipe (os.pipe()). Have a parent process to track state.

Fork each child.

In each child: close the read end of the pipe. Do stuff. When finished,
close the write end of the pipe.

In the parent, after forking all children: close the write end of the
pipe. Read from the read end. When all the children have finished
they will have closed all the write ends and you will see EOF
on the read end of the pipe.

For extra credit you can have the children write some sort of
success/failure byte to the pipe before closing. Counting and examinine
these bytes in the parent can tell you about individual failure if you
care.

| (3) Current thought is to break the process from a method into a
| external
| script; call the script in separate threads.  This is the only way I
| can see
| to give each process a separate dir (external process fixes that), and
| I can
| find out when each process is finished (thread fixes that).

Yeah, that'll work:

  for child in 1 2 3 4 5 6 ...
  do
mkdir workdir
( cd work-dir; run-child ) &
  done
  wait

| Am I missing something? Is there a better way? I hate to rewrite this
| method
| as a script since I've got a lot of object metadata that I'll have to
| regenerate with each call of the script.

See the pipe scheme in point (2) above. Doubtless there are other
methods, but pipes are each shared resources with the right behaviour.
I'd prefer method (1) myself, assuming you have control of the working
file paths.

Cheers,
-- 
Cameron Simpson <[EMAIL PROTECTED]> DoD#743
http://www.cskk.ezoshosting.com/cs/

If everyone is thinking alike, then someone isn't thinking. - Patton
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Aaron "Castironpi" Brady
On Sep 24, 8:40 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> On Sep 25, 3:16 am, Pete Forman <[EMAIL PROTECTED]> wrote:
>
> > Asun Friere <[EMAIL PROTECTED]> writes:
>
> >  > A canonical use of the conditional operator is in
> >  > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').
>
> > That fails for n == 1.  So what is best?
>
> Sorry missing parantheses.  I should test, even for fragments written
> out as part of a sentence. %-/
>
> > for i in range(4):
> >     print '%d thing' % i + ('s' if i != 1 else '')
>
> That's the corrected version of what I meant, but actually I think
> your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
> all variables for placeholders in the tuple, is better. It's certainly
> more readible.

It's a different answer if you have 'things is/are'.  '%d thing%s %s'%
( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ).  Or excluding
prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's
are' if i!= 1 else ' is' ).
--
http://mail.python.org/mailman/listinfo/python-list


Re: multiple processes, private working directories

2008-09-24 Thread r0g
Tim Arnold wrote:
> I have a bunch of processes to run and each one needs its own working
> directory. I'd also like to know when all of the processes are
> finished.
> 
> (1) First thought was threads, until I saw that os.chdir was process-
> global.
> (2) Next thought was fork, but I don't know how to signal when each
> child is
> finished.
> (3) Current thought is to break the process from a method into a
> external
> script; call the script in separate threads.  This is the only way I
> can see
> to give each process a separate dir (external process fixes that), and
> I can
> find out when each process is finished (thread fixes that).
> 
> Am I missing something? Is there a better way? I hate to rewrite this
> method
> as a script since I've got a lot of object metadata that I'll have to
> regenerate with each call of the script.
> 
> thanks for any suggestions,
> --Tim Arnold

(1) + avoid os.chdir and maintain hard paths to all files/folders? or
(2) + sockets? or
(2) + polling your systems task list?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 3:16 am, Pete Forman <[EMAIL PROTECTED]> wrote:
> Asun Friere <[EMAIL PROTECTED]> writes:
>
>  > A canonical use of the conditional operator is in
>  > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').
>
> That fails for n == 1.  So what is best?
>

Sorry missing parantheses.  I should test, even for fragments written
out as part of a sentence. %-/

> for i in range(4):
> print '%d thing' % i + ('s' if i != 1 else '')
>

That's the corrected version of what I meant, but actually I think
your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
all variables for placeholders in the tuple, is better. It's certainly
more readible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 3:16 am, Pete Forman <[EMAIL PROTECTED]> wrote:
> Asun Friere <[EMAIL PROTECTED]> writes:
>
>  > A canonical use of the conditional operator is in
>  > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').
>
> That fails for n == 1.  So what is best?
>

Sorry missing parentheses.  I should test before posting, even for
code written into.

> for i in range(4):
> print '%d thing' % i + ('s' if i != 1 else '')

That is the correct version of what I meant, but your last, including
all variables for placeholders in the tuple is probably better.
--
http://mail.python.org/mailman/listinfo/python-list


multiple processes, private working directories

2008-09-24 Thread Tim Arnold
I have a bunch of processes to run and each one needs its own working
directory. I'd also like to know when all of the processes are
finished.

(1) First thought was threads, until I saw that os.chdir was process-
global.
(2) Next thought was fork, but I don't know how to signal when each
child is
finished.
(3) Current thought is to break the process from a method into a
external
script; call the script in separate threads.  This is the only way I
can see
to give each process a separate dir (external process fixes that), and
I can
find out when each process is finished (thread fixes that).

Am I missing something? Is there a better way? I hate to rewrite this
method
as a script since I've got a lot of object metadata that I'll have to
regenerate with each call of the script.

thanks for any suggestions,
--Tim Arnold
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread Grant Edwards
On 2008-09-24, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> hrishy a écrit :
> (snip)
>
>
>> I apologise
>> (I thought Python programmers were smart and they did know what LINQ was)
>
> Is there really any relation between "being smart" and knowing anything 
> about the latest MS fad ?

God, I hope not -- or I'd rather be stupid.

-- 
Grant

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


Er, one -lime- or two.

2008-09-24 Thread Aaron "Castironpi" Brady
A Python walks into a bar and orders a complex data structure.
Bartender says, "One line or two?"
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyRun_SimpleFile() crashes

2008-09-24 Thread lixinyi . 23
On 9月25日, 午前1:05, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
wrote:
> On Sep 24, 6:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > >  my code:
> > >  main.cpp
> > >  #include 
>
> > >  int main(int argc, char **argv)
> > >  {
> > >  Py_Initialize();
>
> > >  FILE *file_1 = fopen("a2l_reader.py","r+");
> > >  PyRun_SimpleFile(file_1,"a2l_reader.py");
>
> > >  Py_Finalize();
> > >  }
>
> > >  compile under windows using MinGW:
> > >  g++ main.cpp libpython25.a -o a
>
> > >  no error was found. But when I run a.exe the program just crashes.
>
> > >  What should I do?
>
> > Run it under gdb (which should have come with MinGW).
>
> > Check that you actually opened the file, ie file_1 != 0.
>
> > This might be relevant
>
> >  http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o...
>
> > --
> > Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick
>
> There's a workaround.
>
> filename = "Entire path of the python file";
> PyObject* PyFileObject = PyFile_FromString(filename, "r");
> PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename);
> // decref PyFileObject
>
> http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567

Wow this one works fine for me.
Thank you!
--
http://mail.python.org/mailman/listinfo/python-list

Re: urllib error on urlopen

2008-09-24 Thread Michael Palmer
On Sep 24, 11:46 am, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have been using the following code for over a year in one of my
> programs:
>
> f = urllib2.urlopen('https://www.companywebsite.com/somestring')
>
> It worked great until the middle of the afternoon yesterday. Now I get
> the following traceback:
>
> Traceback (most recent call last):
>   File "", line 1, in 
> response = urllib2.urlopen(req).read().strip()
>   File "c:\python25\lib\urllib2.py", line 124, in urlopen
> return _opener.open(url, data)
>   File "c:\python25\lib\urllib2.py", line 381, in open
> response = self._open(req, data)
>   File "c:\python25\lib\urllib2.py", line 399, in _open
> '_open', req)
>   File "c:\python25\lib\urllib2.py", line 360, in _call_chain
> result = func(*args)
>   File "c:\python25\lib\urllib2.py", line 1115, in https_open
> return self.do_open(httplib.HTTPSConnection, req)
>   File "c:\python25\lib\urllib2.py", line 1082, in do_open
> raise URLError(err)
> URLError:  routines:SSL23_GET_SERVER_HELLO:unknown protocol')>
>
> I tried my Google Fu on this error, but there's not much out there. I
> tried using a proxy in Python, but that returned the same traceback.
> If I copy the URL into my browser, it resolves correctly. Does anyone
> have any advice on how to troubleshoot this error?
>
> I am using Python 2.5.2 on Windows XP.
>
> Thanks,
>
> Mike

Could it just be a misconfiguration at the other end? Can you open
other https urls?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making small executive file for distribution

2008-09-24 Thread Marin Brkic
On Wed, 24 Sep 2008 14:50:56 -0700 (PDT), sturlamolden
<[EMAIL PROTECTED]> wrote:

>On Sep 24, 3:17 pm, Marin Brkic <[EMAIL PROTECTED]> wrote:
>
>> Has anyone had a situation like this ? All your inputs and suggestions
>> are more then welcomed.
>
>Send them the .py file and confirm that it does work. The lack of
>Python can be blamed on the incompetent BOFH. Chances are the
>situation will change when the BOFH gets 20 requests for Python a
>day.
>

Yes, I agree. But in large institutions, where system engineers
maintain a lot of computers there usually exists a policy on what is
installed on computers and what is not. And currently python is not.
And it's not gonna change anytime soon since only few of us are using
it (2 of us use it on personal laptops, to others we send exe files).

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


Re: Folder Actions on Mac OSX Leopard?

2008-09-24 Thread Sean DiZazzo
On Sep 24, 12:31 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Greetings,
>
> I've been trying to figure out if it's possible to attach a Python
> script to an action via Mac OSX Leopard's File Actions system. I'm
> wanting to call a Python script every time a file is added to the
> monitored folder. Just adding a .py file doesn't seem to do anything
> at all, and I can't find any log output anywhere to see what's going
> on.
>
> I'm more just looking to see if this is or is not possible. I'm not
> interested in other solutions, as I already have them lined up in case
> this is a no-go, but I'd really love to be able to do it this way if
> anyone has any experience. Googling around revealed pretty much
> nothing.
>
> Any help is much appreciated,
> Greg

I always wondered about Folder Actions...  I just tested.  You can
have applescript call python scripts via `do shell script`.  But it
seemed a bit flakey.

I would either go with applescript all the way, or look in to your
other options.

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


Re: Folder Actions on Mac OSX Leopard?

2008-09-24 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

Greetings,

I've been trying to figure out if it's possible to attach a Python
script to an action via Mac OSX Leopard's File Actions system. I'm
wanting to call a Python script every time a file is added to the
monitored folder. Just adding a .py file doesn't seem to do anything
at all, and I can't find any log output anywhere to see what's going
on.

I'm more just looking to see if this is or is not possible. I'm not
interested in other solutions, as I already have them lined up in case
this is a no-go, but I'd really love to be able to do it this way if
anyone has any experience. Googling around revealed pretty much
nothing.


You mean this?

http://developer.apple.com/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/chapter_2_section_1.html

*I* would use ctypes to access Carbon Core. But then that's just me - 
I'm sure you find a better way...


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


Re: Linq to Python

2008-09-24 Thread Thomas G. Willis
On Sep 24, 4:59 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
...
> I haven't yet had occasion to use LINQ in anger yet, so I have no idea
> whether its an idea to love or to hate. I do think it is good that C# has
> effectively sprouted list comprehensions (not to mention anonymous types
> and type inferencing) and I expect there may be some aspects worth looking
> at for Python but I think they are more likely to lead to itertools
> functions than extensions to syntax.

My thoughts exactly when I first looked at it. "Hey C# NOW has list
comprehensions!!! SWEET!!!"

As I understand it LINQ is libraries(System.Data.Linq.dll,
System.XML.Linq.dll) + syntactic sugar, i wouldn't call that a change
to the language. The addition of lambdas and functions as first class
objects however, that was indeed a language change, and it was a
change for the better that makes LINQ possible, (also makes writing
delegates less cumbersome). To someone other than a C# person, these
features are not new or revolutionary, it's just C# catching up. Kudos
to them for getting there before java.

After some more thought on what might conceivably be missing from
python that LINQ has, that someone might want is the equivalent of
System.XML.Linq.dll, and I can't see any reason why someone couldn't
write it with the exception that there doesn't seem to be a definitive
XML lib for python, meaning generally regarded as the best. That in my
mind would be a prerequisite. But if someone wrote both the XML lib
with the LINQ-ish syntax, maybe it would become the definitive XML
lib.

Again, I personally don't see myself using XML and thus needing that
unless my hand was forced by some business requirement that dictated I
use XML, I would not use it if I had a choice. The SQL LiNQ-ish
though, I think every python ORM has that covered to a degree, and I
use that quite a bit.



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


Re: Schwartzian transform for tuple in list

2008-09-24 Thread David Di Biase
When you say slightly, is it enough to make a difference? Why would  
getitems be faster even - not sure I can think why...


Sent from my iPhone

On 24-Sep-08, at 5:46 PM, Matt Nordhoff <[EMAIL PROTECTED]>  
wrote:



Chris Rebert wrote:
On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase <[EMAIL PROTECTED] 
> wrote:

Hi,

I have a rather large list structure with tuples contained in them  
(it's

part of a specification I received) looks like so:
[(x1,y1,r1,d1),(x2,y2,r2,d2)...]

The list can range from about 800-1500 tuples in size and I'm  
currently

sorting it with this:

a_list.sort(lambda a, b: cmp(b[3], a[3]))


You'd probably be better off using the 'key' keyword argument to
.sort(), which is made for the Schwartzian Transform:

a_list.sort(key=lambda x: x[3])

This sorts the list items by the value produced by the key function
for each item. It's also (IIRC) faster than using a comparison
function like you're currently doing.

Regards,
Chris


Yes, using 'key' is faster than 'cmp'.

If you have Python 2.4 or newer, it would also be slightly faster to  
use

operator.itemgetter() instead of a lambda:


import operator
a_list.sort(key=operator.itemgetter(3))


I'm actually sorting it by the last value in the tuple (d2). I  
have been
researching more efficient sorting algorithms and came across  
Schwartzian

transform via these links:

http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency
http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html

I get what's happening (sorta...errr...lol)  but I'm not sure if  
it is more
efficient in my scenario, if it is then I have no idea how to  
implement it

properly :-/

Would be great if a true expert would offer a suggestion for me...

Thanks!

David

--

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


is decorator the right thing to use?

2008-09-24 Thread Dmitry S. Makovey
Hi,

after hearing a lot about decorators and never actually using one I have
decided to give it a try. My particular usecase is that I have class that
acts as a proxy to other classes (i.e. passes messages along to those
classes) however hand-coding this type of class is rather tedious, so I
decided to use decorator for that. Can somebody tell me if what I'm doing
is a potential shot-in-the-foot or am I on the right track? (Note, It's
rather rudimentary proof-of-concept implementation and not the final
solution I'm about to employ so there are no optimizations or
signature-preserving code there yet, just the idea).

Here's the code:

class A:
b=None
def __init__(self,b):
self.val='aval'
self.b=b
b.val='aval'

def mymethod(self,a):
print "A::mymethod, ",a

def mymethod2(self,a):
print "A::another method, ",a


def Aproxy(fn):
def delegate(*args,**kw):
print "%s::%s" % (args[0].__class__.__name__,fn.__name__)
args=list(args)
b=getattr(args[0],'b')
fnew=getattr(b,fn.__name__)
# get rid of original object reference
del args[0]
fnew(*args,**kw)
setattr(A,fn.__name__,delegate)
return fn

class B:
def __init__(self):
self.val='bval'

@Aproxy
def bmethod(self,a):
print "B::bmethod"
print a, self.val

@Aproxy
def bmethod2(self,a):
print "B::bmethod2"
print a, self.val

b=B()
b.bmethod('foo')
a=A(b)
b=B()
b.val='newval'
a.bmethod('bar')
a.bmethod2('zam')


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


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Craig Allen

> Why, yes, I am wearing my BOFH hat. How could you tell?
>
> --
> Tim Rowe


evil, but I think you may be a BSEFH, not a BOFH.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making small executive file for distribution

2008-09-24 Thread sturlamolden
On Sep 24, 3:17 pm, Marin Brkic <[EMAIL PROTECTED]> wrote:

> Has anyone had a situation like this ? All your inputs and suggestions
> are more then welcomed.

Send them the .py file and confirm that it does work. The lack of
Python can be blamed on the incompetent BOFH. Chances are the
situation will change when the BOFH gets 20 requests for Python a
day.


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


Re: Schwartzian transform for tuple in list

2008-09-24 Thread Matt Nordhoff
Chris Rebert wrote:
> On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I have a rather large list structure with tuples contained in them (it's
>> part of a specification I received) looks like so:
>> [(x1,y1,r1,d1),(x2,y2,r2,d2)...]
>>
>> The list can range from about 800-1500 tuples in size and I'm currently
>> sorting it with this:
>>
>> a_list.sort(lambda a, b: cmp(b[3], a[3]))
> 
> You'd probably be better off using the 'key' keyword argument to
> .sort(), which is made for the Schwartzian Transform:
> 
> a_list.sort(key=lambda x: x[3])
> 
> This sorts the list items by the value produced by the key function
> for each item. It's also (IIRC) faster than using a comparison
> function like you're currently doing.
> 
> Regards,
> Chris

Yes, using 'key' is faster than 'cmp'.

If you have Python 2.4 or newer, it would also be slightly faster to use
operator.itemgetter() instead of a lambda:

>>> import operator
>>> a_list.sort(key=operator.itemgetter(3))

>> I'm actually sorting it by the last value in the tuple (d2). I have been
>> researching more efficient sorting algorithms and came across Schwartzian
>> transform via these links:
>>
>> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency
>> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html
>>
>> I get what's happening (sorta...errr...lol)  but I'm not sure if it is more
>> efficient in my scenario, if it is then I have no idea how to implement it
>> properly :-/
>>
>> Would be great if a true expert would offer a suggestion for me...
>>
>> Thanks!
>>
>> David
-- 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread sturlamolden
On Sep 24, 10:59 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:

> Simple LINQ expressions like the one you gave map easily to Python list
> comprehensions. What Microsoft have done though is provide a consistent
> implementation which allows you to write complex SQL like expressions which
> will work identically on databases or most other sequence types.
> han extensions to syntax.

List comprehensions work with any iterable sequence. You can nest them
to make more complex statements. You can also use a generator to
iterate through a database or an XML document. Here is approximately
where linq stops being a marvelous addition to Python.

And I can honestly do without the SQL syntax.





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


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Ross Ridge
Grant Edwards  <[EMAIL PROTECTED]> wrote:
> Same here.  It's like an automotive engine controls designer
> asking if a failed O2 sensor should turn on the check engine
> light or blow up the car.
 
Ross Ridge <[EMAIL PROTECTED]> wrote:
> No, it's more like asking if the failed sensor should turn on
> a strange and mysterious light on the dashboard
 
Grant Edwards  <[EMAIL PROTECTED]> wrote:
> You're right.  I had forgotten that sys.exit() is actually
> raising the system exit exception, and that the application
> calling the library could handle that exception.
 
Ross Ridge a écrit :
> Well, my point was that exceptions in Python are a bit like a car's
> check engine light.  Few drivers know what this mysterious light means,
> and aren't prepared to do anything about it when it goes on.

Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>You're kidding, aren't you ?

Of course not.  Plenty of people were quick to say that the exception
should be passed through to the caller.  No one said this behaviour
should be documented.  There may be little practical difference bewteen
calling sys.exit() after printing an error and progating an exception
if no one using the library knows that it could generate that exception
in those circumstances.

Ross Ridge

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

Re: Schwartzian transform for tuple in list

2008-09-24 Thread Chris Rebert
On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a rather large list structure with tuples contained in them (it's
> part of a specification I received) looks like so:
> [(x1,y1,r1,d1),(x2,y2,r2,d2)...]
>
> The list can range from about 800-1500 tuples in size and I'm currently
> sorting it with this:
>
> a_list.sort(lambda a, b: cmp(b[3], a[3]))

You'd probably be better off using the 'key' keyword argument to
.sort(), which is made for the Schwartzian Transform:

a_list.sort(key=lambda x: x[3])

This sorts the list items by the value produced by the key function
for each item. It's also (IIRC) faster than using a comparison
function like you're currently doing.

Regards,
Chris

>
> I'm actually sorting it by the last value in the tuple (d2). I have been
> researching more efficient sorting algorithms and came across Schwartzian
> transform via these links:
>
> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency
> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html
>
> I get what's happening (sorta...errr...lol)  but I'm not sure if it is more
> efficient in my scenario, if it is then I have no idea how to implement it
> properly :-/
>
> Would be great if a true expert would offer a suggestion for me...
>
> Thanks!
>
> David
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Schwartzian transform for tuple in list

2008-09-24 Thread David Di Biase
Hi,

I have a rather large list structure with tuples contained in them (it's
part of a specification I received) looks like so:
[(x1,y1,r1,d1),(x2,y2,r2,d2)...]

The list can range from about 800-1500 tuples in size and I'm currently
sorting it with this:

a_list.sort(lambda a, b: cmp(b[3], a[3]))

I'm actually sorting it by the last value in the tuple (d2). I have been
researching more efficient sorting algorithms and came across Schwartzian
transform via these links:

   -
   http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency
   -
   
http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html

I get what's happening (sorta...errr...lol)  but I'm not sure if it is more
efficient in my scenario, if it is then I have no idea how to implement it
properly :-/

Would be great if a true expert would offer a suggestion for me...

Thanks!

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

Re: Linq to Python

2008-09-24 Thread Duncan Booth
r0g <[EMAIL PROTECTED]> wrote:

> OK so maybe I'm being naive here but it looks to me like this new
> paradigm's big idea is to use a python + SQL type syntax to access data
> in random objects. Big whoop. It's not that difficult to write a
> generators that wraps XML files and databases is it?
> 
> What am I missing here?

Simple LINQ expressions like the one you gave map easily to Python list 
comprehensions. What Microsoft have done though is provide a consistent 
implementation which allows you to write complex SQL like expressions which 
will work identically on databases or most other sequence types.

Here's another LINQ example:

   List customers = GetCustomerList();
 
   var customerOrderGroups = 
   from c in customers
   select
   new {c.CompanyName, 
YearGroups =
from o in c.Orders
  group o by o.OrderDate.Year into yg
  select
  new {Year = yg.Key,
   MonthGroups = 
 from o in yg
 group o by o.OrderDate.Month into mg
 select new { Month = mg.Key, Orders = mg }
  }
};
   
   ObjectDumper.Write(customerOrderGroups, 3);

I'm not overly keen on SQL syntax: I think this sort of complex expression 
is hard to read. LINQ has a pretty straightforward conversion to method 
calls, and for me this consistent set of methods is the important thing 
rather than the SQL syntax. e.g. 'group by' maps directly to a call to a 
method GroupBy(), so another of Microsoft's LINQ examples is:

public void Linq45() {
string[] anagrams = {"from ", " salt", " earn ", " last ",
 " near ", " form "};
 
var orderGroups = anagrams.GroupBy(
w => w.Trim(), 
a => a.ToUpper(),
new AnagramEqualityComparer()
);
   
ObjectDumper.Write(orderGroups, 1);
}
 
public class AnagramEqualityComparer : IEqualityComparer
{
public bool Equals(string x, string y) {
return getCanonicalString(x) == getCanonicalString(y);
}
 
public int GetHashCode(string obj) {
return getCanonicalString(obj).GetHashCode();
}

private string getCanonicalString(string word) {
char[] wordChars = word.ToCharArray();
Array.Sort(wordChars);
return new string(wordChars);
}
}

Python still wins hands down on this example both in verbosity and 
readability:

>>> anagrams = ["from ", " salt", " earn ", " last ",
 " near ", " form "]
>>> from itertools import groupby
>>> def AnagramKey(w):
return sorted(w.strip().upper())

>>> for k,words in groupby(sorted(anagrams, key=AnagramKey), 
key=AnagramKey):
for w in words:
print w.strip().upper()
print "..."


EARN
NEAR
...
SALT
LAST
...
FROM
FORM
...

I haven't yet had occasion to use LINQ in anger yet, so I have no idea 
whether its an idea to love or to hate. I do think it is good that C# has 
effectively sprouted list comprehensions (not to mention anonymous types 
and type inferencing) and I expect there may be some aspects worth looking 
at for Python but I think they are more likely to lead to itertools 
functions than extensions to syntax.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread sturlamolden
On Sep 24, 9:11 pm, [EMAIL PROTECTED] wrote:

> In the meantime where I
> live lot of people will keep using C# instead of Python and CLisp,
> natural selection at work indeed.

Please explain to me what Linq can do that Python does not. Put you
emphasis on why this can't be done with a library, and thus will
require addition of new syntax to the language.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread Bruno Desthuilliers

hrishy a écrit :
(snip)



I apologise
(I thought Python programmers were smart and they did know what LINQ was)


Is there really any relation between "being smart" and knowing anything 
about the latest MS fad ?

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

Fwd: Twisted vs. CherryPy vs. ??? for light-weight web servers

2008-09-24 Thread Michael Mabin
I just want to be able to write simple scripts to serve xml data and don't
want the headache of administrating an apache server.  I want to collect
some data from some of our production servers and share them with a
sharepoint website.

On Wed, Sep 24, 2008 at 12:29 PM, Jean-Paul Calderone <[EMAIL PROTECTED]>wrote:

> On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin <[EMAIL PROTECTED]>
> wrote:
>
>> Is there any consensus on what the best lightweight web-server is?  Or
>> rather would Twisted be a better choice to choose as a framework that
>> allows
>> me to serve html or xml data for light webservices. Or is CherryPy just as
>> good?
>>
>>
> You haven't described the problem you want to solve in very much detail.  I
> can't tell, for example, why I shouldn't recommend that you use Apache
> instead
> of CherryPy or Twisted or anything else.  Apache has a huge user community,
> lots of documentation, and lots of developers fixing its bugs and making it
> work well.  What are you trying to do that would make Apache a bad choice?
>
> Jean-Paul
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |



-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
--
http://mail.python.org/mailman/listinfo/python-list

empty csv file attachments

2008-09-24 Thread Bobby Roberts
hi group.

I'm new to python but a veteran at programming.  This one has me
stumped.  I have a simple contact form which the user fills out.  The
email is sent to the site user as well and it is delivered with the
content in the body of the email as well in nice order.  I have
modified my code to also send the content as a csv attachment.  On the
server, the file is perfectly generated with content.  The attachment,
however, is completely blank.  Any ideas what that could be?  My code
snippet is shown below:


  if int(attachmenttype)==2 or int(attachmenttype)==3:
for field in ctx.request.field_names():
  if field=='last_name':
myfilename=ctx.request.field_value(field)+'.txt'
if myfilename=='':
  myfilename='tempfile.txt'
mypath= mynewfilepath + '/' + myfilename
f=open(mypath, 'w')
mynewstring=''
counter=0
for field in ctx.request.field_names():
  if field != 'inquiry_required':
mynewstring=mynewstring + field +','
if mynewstring[-1]==',':
  mynewstring=mynewstring[0:len(mynewstring)-1]
f.write(mynewstring)
f.write ('\n')

mynewstring=''
counter=1
for field in ctx.request.field_names():
  fielddata=ctx.request.field_value(field)
  if counter==1:
dummydata=0
  else:
mynewstring=mynewstring + '"' + fielddata.replace('"','')
+ '",'
  counter = counter + 1
if mynewstring[-1]==',':
  mynewstring=mynewstring[0:len(mynewstring)-1]
f.write(mynewstring)
f.write('\n')
f.close
attachments.append('/'.join((ctx.request.library,
myfilename)))

 [snip... sends email just after this]

any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread r0g
[EMAIL PROTECTED] wrote:
> sturlamolden:
>> No, because Python already has list comprehensions and we don't need the XML 
>> buzzword.<
> 
> LINQ is more than buzzwords. Python misses several of those features.
> So maybe for once the Python crowd may recognize such C# feature as
> much better than things present in Python.
> Said that, I presume Python will go on as usual, and LINQ-like
> capabilities will not be integrated in Python. In the meantime where I
> live lot of people will keep using C# instead of Python and CLisp,
> natural selection at work indeed.
> 
> Bye,
> bearophile

LOL, I just read that and thought - Ok this sounds serious I'd better go
 find out what this LINQ business is all about so I googled.. and ended
up on MSDN where there's impressive sounding talk about how we need a
way to query databases and XML files with a unified syntax like we do
for for standard datatypes like files and arrays. Well yes,that makes
sense I think and proceed to look at their example code, curious as to
what this new paradigm looks like:

using System;
using System.Linq;
using System.Collections.Generic;

class app {
  static void Main() {
string[] names = { "Burke", "Connor", "Frank",
   "Everett", "Albert", "George",
   "Harris", "David" };

IEnumerable query = from s in names
   where s.Length == 5
   orderby s
   select s.ToUpper();

foreach (string item in query)
  Console.WriteLine(item);
  }
}

ROTFLMAO! Wow, what progress they're making! Quick guys let's jump on
before we get left behind - we dont want to miss out on this exciting
and mysterious 'foreach' construct or this strange and exotic sounding
'IEnumerable query' thing. To think that python might someday reach such
lofty heights where we'll be able to simply write...

names = ["Burke", "Connor", "Frank", "Everett",
 "Albert", "George", "Harris", "David"]

result = [each.upper() for each in names if len(each) == 5]

result.sort()

for each in result: print each


Yes clearly 'the Python crowd' must admit LINQ is 'much better', I'm
sold, in fact off to download my "Free, but limited editions of Visual
Studio 2005 for a single programming language supported by .NET" right away!

OK so maybe I'm being naive here but it looks to me like this new
paradigm's big idea is to use a python + SQL type syntax to access data
in random objects. Big whoop. It's not that difficult to write a
generators that wraps XML files and databases is it?

What am I missing here?


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


empty csv file attachments

2008-09-24 Thread Bobby Roberts
hi group.

I'm new to python but a veteran at programming.  This one has me
stumped.  I have a simple contact form which the user fills out.  The
email is sent to the site user as well and it is delivered with the
content in the body of the email as well in nice order.  I have
modified my code to also send the content as a csv attachment.  On the
server, the file is perfectly generated with content.  The attachment,
however, is completely blank.  Any ideas what that could be?  My code
snippet is shown below:


  if int(attachmenttype)==2 or int(attachmenttype)==3:
for field in ctx.request.field_names():
  if field=='last_name':
myfilename=ctx.request.field_value(field)+'.txt'
if myfilename=='':
  myfilename='tempfile.txt'
mypath= mynewfilepath + '/' + myfilename
f=open(mypath, 'w')
mynewstring=''
counter=0
for field in ctx.request.field_names():
  if field != 'inquiry_required':
mynewstring=mynewstring + field +','
if mynewstring[-1]==',':
  mynewstring=mynewstring[0:len(mynewstring)-1]
f.write(mynewstring)
f.write ('\n')

mynewstring=''
counter=1
for field in ctx.request.field_names():
  fielddata=ctx.request.field_value(field)
  if counter==1:
dummydata=0
  else:
mynewstring=mynewstring + '"' + fielddata.replace('"','')
+ '",'
  counter = counter + 1
if mynewstring[-1]==',':
  mynewstring=mynewstring[0:len(mynewstring)-1]
f.write(mynewstring)
f.write('\n')
f.close
attachments.append('/'.join((ctx.request.library,
myfilename)))

 [snip... sends email just after this]

any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


online pharmacy perscription.dt8v1

2008-09-24 Thread gherlylu
Start saving, best online pharmacy here 
http://defgjkmahl.nufehrurald.net/?bciahlxwvrsydefgjkzchcmm
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyRun_SimpleFile() crashes

2008-09-24 Thread Aaron "Castironpi" Brady
On Sep 24, 11:05 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 24, 6:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > >  my code:
> > >  main.cpp
> > >  #include 
>
> > >  int main(int argc, char **argv)
> > >  {
> > >  Py_Initialize();
>
> > >  FILE *file_1 = fopen("a2l_reader.py","r+");
> > >  PyRun_SimpleFile(file_1,"a2l_reader.py");
>
> > >  Py_Finalize();
> > >  }
>
> > >  compile under windows using MinGW:
> > >  g++ main.cpp libpython25.a -o a
>
> > >  no error was found. But when I run a.exe the program just crashes.
>
> > >  What should I do?
>
> > Run it under gdb (which should have come with MinGW).
>
> > Check that you actually opened the file, ie file_1 != 0.
>
> > This might be relevant
>
> >  http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o...
>
> > --
> > Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick
>
> There's a workaround.
>
> filename = "Entire path of the python file";
> PyObject* PyFileObject = PyFile_FromString(filename, "r");
> PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename);
> // decref PyFileObject
>
> http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567

Just to follow up-- The links say that the crash comes from opening a
file with two different versions of a library.  Would it be possible
to get an API entry point to the version the build uses?

It does use the 'fopen' function by name, but not the same version.
And creating the entire object just to get its f_fp field is really
long.
--
http://mail.python.org/mailman/listinfo/python-list


Quick & Secured Pharmacy Online. rdjr0

2008-09-24 Thread gherlylu
Start saving, best online pharmacy here 
http://fjmgilbh.zarubanlo.net/?acdekbhxwvrsyfjmzchcmgil
--
http://mail.python.org/mailman/listinfo/python-list


Folder Actions on Mac OSX Leopard?

2008-09-24 Thread [EMAIL PROTECTED]
Greetings,

I've been trying to figure out if it's possible to attach a Python
script to an action via Mac OSX Leopard's File Actions system. I'm
wanting to call a Python script every time a file is added to the
monitored folder. Just adding a .py file doesn't seem to do anything
at all, and I can't find any log output anywhere to see what's going
on.

I'm more just looking to see if this is or is not possible. I'm not
interested in other solutions, as I already have them lined up in case
this is a no-go, but I'd really love to be able to do it this way if
anyone has any experience. Googling around revealed pretty much
nothing.

Any help is much appreciated,
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Bruno Desthuilliers

Ross Ridge a écrit :
(snip)

Grant Edwards  <[EMAIL PROTECTED]> wrote:

Same here.  It's like an automotive engine controls designer
asking if a failed O2 sensor should turn on the check engine
light or blow up the car.


Ross Ridge <[EMAIL PROTECTED]> wrote:

No, it's more like asking if the failed sensor should turn on
a strange and mysterious light on the dashboard


Grant Edwards  <[EMAIL PROTECTED]> wrote:

You're right.  I had forgotten that sys.exit() is actually
raising the system exit exception, and that the application
calling the library could handle that exception.


Well, my point was that exceptions in Python are a bit like a car's
check engine light.  Few drivers know what this mysterious light means,
and aren't prepared to do anything about it when it goes on.


You're kidding, aren't you ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-24 Thread Chris Mellon
On Wed, Sep 24, 2008 at 2:11 PM,  <[EMAIL PROTECTED]> wrote:
> sturlamolden:
>>No, because Python already has list comprehensions and we don't need the XML 
>>buzzword.<
>
> LINQ is more than buzzwords. Python misses several of those features.
> So maybe for once the Python crowd may recognize such C# feature as
> much better than things present in Python.
> Said that, I presume Python will go on as usual, and LINQ-like
> capabilities will not be integrated in Python. In the meantime where I
> live lot of people will keep using C# instead of Python and CLisp,
> natural selection at work indeed.
>

Why do you swing so widely between being an interesting poster with
interesting, useful things to say and mindless trolling? There's a lot
of reasons to use C# instead of Python or Lisp (or any other language
for that matter), but I can't imagine that someone would make that
decision based solely on LINQ. I'd go so far as to say that if they
do, I question their professional competence.

LINQ is an interesting implementation of an old idea. The place where
it differs from list comps is that it has appropriate hooks for the
specific linq implementation to override the way results are gathered,
and such hooks in Python would be an interesting idea. I've taken a
shot and figuring out where and how they should be implemented, but I
haven't come up with anything I like. Maybe you should try it?

LINQs "native" object API (not the syntax sugar available in C#) is
not very different from Python ORMs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python GUI development using XULRunner

2008-09-24 Thread Joe Hrbek
Todd, this is great!  Thanks for your work on this.  I've been using
your extension for awhile, successfully creating little apps.  Your
gui_app template has been a huge help in advancing my understanding of
how things fit together...takes some of the guesswork out. :)  Thanks
again,

-j

On Sep 16, 8:29 pm, Todd Whiteman <[EMAIL PROTECTED]> wrote:
> I've put together a tutorial that shows off how to build a GUI
> application using XULRunner (same architectural components as Firefox
> uses) that can be used in conjunction with the Python programming language.
>
> The tutorial covers how to build a Python/XULRunner GUI 
> application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul...
>
> The details in this tutorial covers the initial setup to full
> packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX
> is possible with a few deviations, I have tried to cover these
> deviations where applicable).
>
> Feedback is welcome.
>
> Cheers,
> Todd

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


RE: More regex help

2008-09-24 Thread Support Desk
Kirk, 

That's exactly what I needed. Thx!
 

-Original Message-
From: Kirk Strauser [mailto:[EMAIL PROTECTED] 
Sent: Wednesday, September 24, 2008 11:42 AM
To: python-list@python.org
Subject: Re: More regex help

At 2008-09-24T16:25:02Z, "Support Desk" <[EMAIL PROTECTED]> writes:

> I am working on a python webcrawler, that will extract all links from an
> html page, and add them to a queue, The problem I am having is building
> absolute links from relative links, as there are so many different types
of
> relative links. If I just append the relative links to the current url,
some
> websites will send it into a never-ending loop. 

>>> import urllib
>>> urllib.basejoin('http://www.example.com/path/to/deep/page',
'/foo')
'http://www.example.com/foo'
>>> urllib.basejoin('http://www.example.com/path/to/deep/page',
'http://slashdot.org/foo')
'http://slashdot.org/foo'

-- 
Kirk Strauser
The Day Companies


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


Re: Linq to Python

2008-09-24 Thread Tim Golden

[EMAIL PROTECTED] wrote:

sturlamolden:

No, because Python already has list comprehensions and we don't need the XML 
buzzword.<


LINQ is more than buzzwords. Python misses several of those features.
So maybe for once the Python crowd may recognize such C# feature as
much better than things present in Python.
Said that, I presume Python will go on as usual, and LINQ-like
capabilities will not be integrated in Python. In the meantime where I
live lot of people will keep using C# instead of Python and CLisp,
natural selection at work indeed.


Perhaps a quick summary of what LINQ offers which might
"be integrated into Python" would help those of us who
are ignorant? (This is a serious comment; I'd like to know).

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


Re: Linq to Python

2008-09-24 Thread bearophileHUGS
sturlamolden:
>No, because Python already has list comprehensions and we don't need the XML 
>buzzword.<

LINQ is more than buzzwords. Python misses several of those features.
So maybe for once the Python crowd may recognize such C# feature as
much better than things present in Python.
Said that, I presume Python will go on as usual, and LINQ-like
capabilities will not be integrated in Python. In the meantime where I
live lot of people will keep using C# instead of Python and CLisp,
natural selection at work indeed.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Ross Ridge
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> Presumably somebody has suggested that calling sys.exit() was a good 
> option. I'm curious to what possible reason they could give for such a 
> poor choice.

Grant Edwards  <[EMAIL PROTECTED]> wrote:
>Same here.  It's like an automotive engine controls designer
>asking if a failed O2 sensor should turn on the check engine
>light or blow up the car.

Ross Ridge <[EMAIL PROTECTED]> wrote:
> No, it's more like asking if the failed sensor should turn on
> a strange and mysterious light on the dashboard

Grant Edwards  <[EMAIL PROTECTED]> wrote:
>You're right.  I had forgotten that sys.exit() is actually
>raising the system exit exception, and that the application
>calling the library could handle that exception.

Well, my point was that exceptions in Python are a bit like a car's
check engine light.  Few drivers know what this mysterious light means,
and aren't prepared to do anything about it when it goes on.

Ross Ridge

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


Re: Linq to Python

2008-09-24 Thread sturlamolden
On Sep 24, 5:22 pm, hrishy <[EMAIL PROTECTED]> wrote:

> Well wouldn't it be a lot easier to query and join a xml source with a 
> relational source with LINQ capabilites in Python.
>
> Hmm what am i missing here is there a site that takes all LINQ examples and 
> does them using list comprehensions and makes them sound easy ?
>
> wasn't python supposed to make everything easy ?


Most Python programmers use other languages as well. I have working
knowledge of C, Matlab, C++, Java, Fortran 95, and C#. Those that
responded to your post know what LINQ are and what LINQ does.

Put simply, Python has dynamic typing, list comprehensions, and is
scriptable (i.e. Python source is structured text). That's why Python
don't
need LINQ and XML the same way as C#.  LINQ and XML is needed because
C#
is a statically typed compiled language. That is:

LINQ: Python has list comprehensions and dynamic typing (C# do not)
XML: Python is structured text (compiled .NET assemblies are not)

Second, minimalistic syntax is a virtue. That is why C is still
around.
Python don't add new syntax sugar every time Redmond invents a new
buzzword. Functions like XML processing are delegated to libraries --
where they belong.

Nobody was saying LINQ is a bad idea for a language like C#.

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


Re: Making small executive file for distribution

2008-09-24 Thread Sebastian Bassi
On Wed, Sep 24, 2008 at 10:17 AM, Marin Brkic
<[EMAIL PROTECTED]> wrote:
> As far as I know py2exe is the only option which can do such a thing
> (make exe files from scripts). Is there a way to make those exe files
> a little smaller (for a small script they easily go up to 5-10 mb).

An alternative solution: Give them a copy of "portable python". It is
a Python enviroment that can be used by just copying its file in a
single directory (to run python from a pendrive for example), with the
need to install any program
It even work in Linux with wine (but you seldon need that since most
modern Linux distros has a uptodate Python setup).
See http://www.portablepython.com/
Best,

-- 
Sebastián Bassi. Diplomado en Ciencia y Tecnología.
Vendo isla: http://www.genesdigitales.com/isla
What's new in Python 3: http://tinyurl.com/5cd89r
Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python is slow?

2008-09-24 Thread sturlamolden

I have updated the cookbook entry for yesterday to also include
parallel processing for large data sets. Even if you're not interested
in kd-trees, it is a good example of what the new multiprocessing
standard module can do. There are still people being scared by the
GIL, thinking it prevents Python from utilizing multicore processors.

http://www.scipy.org/Cookbook/KDTree
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making small executive file for distribution

2008-09-24 Thread Marin Brkic
On Wed, 24 Sep 2008 07:32:56 -0700 (PDT), [EMAIL PROTECTED] wrote:

>If you don't create a monolithic EXE, then most of the extra files
>(that make up the bulk of the size) can be shared between other
>converted scripts. That is, if you convert foo.py, and send the bundle
>to your colleague, then convert bar.py, you only need to send bar.exe,
>and it will run fine if they execute it in the same directory that has
>all the DLLs you sent with foo.exe.
>
>Another option might be to encourage them to download Portable Python,
>which doesn't need to be installed.

This is an interesting suggestion. I didn't know there was a portable
version of python. I will look into it - could just turn out to be the
perfect solution to this (after all, it would be even simpler if they
could send/receive just .py script).

Thank you.

--
Marin

>
>Mark Sherry
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem updating variable in a module

2008-09-24 Thread Terry Reedy

[EMAIL PROTECTED] wrote:

Hi,

I've a problem updating my variable in a module.

In my main program, I call a function from mod1 to update a variable of mod1
As soon as I update this varibale, I check it back in the mail program 
but it the variable from mod1 does not get updated.


main Program:

import mod1
a = 20
mod.update(a)
print mod.a   < does not print anything


As Tim noted, this cannot run.
***  Always post the code you actually ran ***
So we cannot answer why the code you did not post did not work.

With the mod/mod1 mixup fixed, you do not need the update function.
  mod.a = 20
should do the same thing.



mod1

a = 10
def update(someInt):
 global a
 a = someInt
 print a < this does actually print a = 20


tjr

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


Re: Twisted vs. CherryPy vs. ??? for light-weight web servers

2008-09-24 Thread Jean-Paul Calderone

On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin <[EMAIL PROTECTED]> wrote:

Is there any consensus on what the best lightweight web-server is?  Or
rather would Twisted be a better choice to choose as a framework that allows
me to serve html or xml data for light webservices. Or is CherryPy just as
good?



You haven't described the problem you want to solve in very much detail.  I
can't tell, for example, why I shouldn't recommend that you use Apache instead
of CherryPy or Twisted or anything else.  Apache has a huge user community,
lots of documentation, and lots of developers fixing its bugs and making it
work well.  What are you trying to do that would make Apache a bad choice?

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


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Pete Forman
Asun Friere <[EMAIL PROTECTED]> writes:

 > A canonical use of the conditional operator is in
 > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').

That fails for n == 1.  So what is best?

for i in range(4):
print '%d thing' % i + ('s' if i != 1 else '')

for i in range(4):
print '%d thing%s' % (i, ('s', '')[i==1])

for i in range(4):
print '%d thing%s' % (i, 's' if i != 1 else '')


-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
[EMAIL PROTECTED]-./\.-   the opinion of Schlumberger or
http://petef.22web.net   -./\.-   WesternGeco.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing float and decimal

2008-09-24 Thread Terry Reedy

Mark Dickinson wrote:

On Sep 23, 7:31 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:

Decimal is something of an anomaly in Python because it was written to
exactly follow an external standard, with no concessions to what would
be sensible for Python.  It is possible that that standard mandates that
Decimals not compare to floats.


I don't think the standard says anything about interactions between
Decimals and floats.


If there is not now, there could be in the future, and the decimal 
authors are committed to follow the standard wherever it goes. 
Therefore, the safe course, to avoid possible future deprecations due to 
doing too much, is to only do what is mandated.



But there's certainly been a feeling amongst at
least some of the developers that the job of Python's decimal module
is to implement the standard and no more, and that extensions to its
functionality belong elsewhere.


For the reason just stated.  A slightly different take is this.  The 
reason for following the standard is so that decimal code in Python is 
exact interconversion both from and to decimal code in other languages. 
 (And one reason for *that* is that one purpose of the standard is to 
reliably implement legal and contractual standards for financial 
calculations.)  Using extensions in Python could break/deprecate code 
translated away from Python.



Regarding equality, there's at least one technical issue:  the
requirement
that objects that compare equal hash equal.  How do you come up with
efficient hash operations for integers, floats, Decimals and Fractions
that satisfy this requirement?


For integral values, this is no problem.
>>> hash(1) == hash(1.0) == hash(decimal.Decimal(1)) == 
hash(fractions.Fraction(1)) == 1

True


For other arithmetic operations:  should the sum of a float and a
Decimal produce a Decimal or a float?  Why?  It's not at all clear to me that
either of these types is 'higher up' the numerical tower than the
other.


Floats and fractions have the same issue.  Fractions are converted to 
floats.  I can think of two reasons: float operations are faster; floats 
are my typically thought of as inexact and since the result is likely to 
be inexact (rounded), float is the more appropriate type to express 
that.  Anyone who disagrees with the choice for their application can 
explicitly convert the float to a fraction.


Decimals can also be converted to floats (they also have a  __float__ 
method).  But unlike fractions, the conversion must be explicit, using 
float(decimal), instead of implicit, as with ints and fractions.


Someone *could* write a PyDecimal wrapper that would do implicit 
conversion and thereby more completely integrate decimals with other 
Python numbers, but I doubt that saving transitivity of equality will be 
sufficient motivation ;-).


Terry Jan Reedy

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


Re: Python is slow?

2008-09-24 Thread sturlamolden

For those who are interested:

I've updated the cookbook tutorial on the kd-tree:

http://scipy.org/Cookbook/KDTree

It now also includes parallel search for multicore CPUs
(multiprocessing standard module). Even if you are not genuinely
interested in kd-trees, it shows how to do parallel processing in
Python despite of the GIL.




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


Re: More regex help

2008-09-24 Thread Kirk Strauser
At 2008-09-24T16:25:02Z, "Support Desk" <[EMAIL PROTECTED]> writes:

> I am working on a python webcrawler, that will extract all links from an
> html page, and add them to a queue, The problem I am having is building
> absolute links from relative links, as there are so many different types of
> relative links. If I just append the relative links to the current url, some
> websites will send it into a never-ending loop. 

>>> import urllib
>>> urllib.basejoin('http://www.example.com/path/to/deep/page',
'/foo')
'http://www.example.com/foo'
>>> urllib.basejoin('http://www.example.com/path/to/deep/page',
'http://slashdot.org/foo')
'http://slashdot.org/foo'

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


Re: how to build a MacOS universal python package including external dependencies

2008-09-24 Thread Mathieu Prevot
2008/9/24 Jaime Huerta Cepas <[EMAIL PROTECTED]>:
> Hi all,
>
> I have developed a set python libraries that provide several scientific
> methods to analyse and visualize certain type of biological data.  This
> libraries are based on many external python modules, such as python-mysql
> python-sip or python-qt4. I use GNU/linux to develop my tools and I found no
> problems into installing all dependencies, however it does not seem to be
> that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 ,
> mysqldb, scipy, numpy) are cross platform, but when you are trying to
> publish your tool in an academic journal, most referees (many of them using
> MacOS) expect some kind of straightforward installation process for the
> tool.
>
> I wonder if there would be a way in which I could compile all the
> dependencies and libraries in a MacOs system and then building a static
> universal binary that I can distribute. I guess  it should be possible, but
> I am not sure how difficult it might be, and whether all dependencies (qt4
> is huge) can be packaged together.

IMHO this is too complex to commit. Macport is a way to do what you
want, but packages may not be up to date enough. Maybe the easiest and
simplest way for you to do this is to write a script that will
download, compile and install everything.

The script should work like:

sudo all_in_one_script.py

and then wait for jobs to be done. Your script will need to know if a
package was sucessfully installed and then continue or take steps and
say it. For a complex set of dependencies, I recommend you to write
Makefiles.

For instance, in pseudo-code:
if /usr/local/lib/libfoo.dylib doesn't exist
  download foo
  install foo

if python-module foo doesn't exist
  download foo
  python foo/setup.py install

etc

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


More regex help

2008-09-24 Thread Support Desk
I am working on a python webcrawler, that will extract all links from an
html page, and add them to a queue, The problem I am having is building
absolute links from relative links, as there are so many different types of
relative links. If I just append the relative links to the current url, some
websites will send it into a never-ending loop. 

What I am looking for is a regexp that will extract the root url from any 
url string I pass to it, such as

'http://example.com/stuff/stuff/morestuff/index.html'

Regexp = http:example.com

'http://anotherexample.com/stuff/index.php

Regexp = 'http://anotherexample.com/

'http://example.com/stuff/stuff/

Regext = 'http://example.com'





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


how to build a MacOS universal python package including external dependencies

2008-09-24 Thread Jaime Huerta Cepas
Hi all,

I have developed a set python libraries that provide several scientific
methods to analyse and visualize certain type of biological data.  This
libraries are based on many external python modules, such as python-mysql
python-sip or python-qt4. I use GNU/linux to develop my tools and I found no
problems into installing all dependencies, however it does not seem to be
that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 ,
mysqldb, scipy, numpy) are cross platform, but when you are trying to
publish your tool in an academic journal, most referees (many of them using
MacOS) expect some kind of straightforward installation process for the
tool.

I wonder if there would be a way in which I could compile all the
dependencies and libraries in a MacOs system and then building a static
universal binary that I can distribute. I guess  it should be possible, but
I am not sure how difficult it might be, and whether all dependencies (qt4
is huge) can be packaged together.

Any help is more than welcome!
Best regards,
Jaime.
--
http://mail.python.org/mailman/listinfo/python-list

Filthy Pink Sneakers. By Marina Cooper

2008-09-24 Thread fernandena
SEXY story. The cute doorman gives me an enigmatic look when I say I'm
here to see you. I am not sure if maybe he thinks I am your daughter.
You are not quite old enough for that, I am not quite young enough -
but we are pretty close. Am I wrong for thinking that's hot?
Definitely. I think...  http://ragdai.info/sex-story.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyRun_SimpleFile() crashes

2008-09-24 Thread Aaron "Castironpi" Brady
On Sep 24, 6:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >  my code:
> >  main.cpp
> >  #include 
>
> >  int main(int argc, char **argv)
> >  {
> >  Py_Initialize();
>
> >  FILE *file_1 = fopen("a2l_reader.py","r+");
> >  PyRun_SimpleFile(file_1,"a2l_reader.py");
>
> >  Py_Finalize();
> >  }
>
> >  compile under windows using MinGW:
> >  g++ main.cpp libpython25.a -o a
>
> >  no error was found. But when I run a.exe the program just crashes.
>
> >  What should I do?
>
> Run it under gdb (which should have come with MinGW).
>
> Check that you actually opened the file, ie file_1 != 0.
>
> This might be relevant
>
>  http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o...
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

There's a workaround.

filename = "Entire path of the python file";
PyObject* PyFileObject = PyFile_FromString(filename, "r");
PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename);
// decref PyFileObject

http://mail.python.org/pipermail/python-list/2007-March/431725.html
http://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567

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


Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Grant Edwards
On 2008-09-24, Ross Ridge <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> Presumably somebody has suggested that calling sys.exit() was a good 
>> option. I'm curious to what possible reason they could give for such a 
>> poor choice.
>
> Grant Edwards  <[EMAIL PROTECTED]> wrote:
>>Same here.  It's like an automotive engine controls designer
>>asking if a failed O2 sensor should turn on the check engine
>>light or blow up the car.
>
> No, it's more like asking if the failed sensor should turn on
> a strange and mysterious light on the dashboard

You're right.  I had forgotten that sys.exit() is actually
raising the system exit exception, and that the application
calling the library could handle that exception.

> and then blow up the car if the driver doesn't immediately
> stop and check the engine.  The owners manual would only
> vaguely hint at the fact that this could happen.

-- 
Grant Edwards   grante Yow! Why is it that when
  at   you DIE, you can't take
   visi.comyour HOME ENTERTAINMENT
   CENTER with you??
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem updating variable in a module

2008-09-24 Thread dudeja . rajat
>I take it you do have a *really* good reason to use a global?

Please suggest some way other than using global. I want to get rid of it
-- 
Regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

urllib error on urlopen

2008-09-24 Thread Mike Driscoll
Hi,

I have been using the following code for over a year in one of my
programs:

f = urllib2.urlopen('https://www.companywebsite.com/somestring')

It worked great until the middle of the afternoon yesterday. Now I get
the following traceback:

Traceback (most recent call last):
  File "", line 1, in 
response = urllib2.urlopen(req).read().strip()
  File "c:\python25\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data)
  File "c:\python25\lib\urllib2.py", line 381, in open
response = self._open(req, data)
  File "c:\python25\lib\urllib2.py", line 399, in _open
'_open', req)
  File "c:\python25\lib\urllib2.py", line 360, in _call_chain
result = func(*args)
  File "c:\python25\lib\urllib2.py", line 1115, in https_open
return self.do_open(httplib.HTTPSConnection, req)
  File "c:\python25\lib\urllib2.py", line 1082, in do_open
raise URLError(err)
URLError: 


I tried my Google Fu on this error, but there's not much out there. I
tried using a proxy in Python, but that returned the same traceback.
If I copy the URL into my browser, it resolves correctly. Does anyone
have any advice on how to troubleshoot this error?

I am using Python 2.5.2 on Windows XP.

Thanks,

Mike

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


Re: Linq to Python

2008-09-24 Thread Thomas G. Willis
On Wed, Sep 24, 2008 at 11:25 AM, hrishy <[EMAIL PROTECTED]> wrote:

> Hi Tom
>
> This is what i like and feel of the Python programmers smarter then every
> other langauge i know of.
>
> But i am not comfortable with your second statement XML i never need it
> one day everybody would need it.
>
>
> regards
> Hrishy
>
>
Well you may be right which is why I said "hopefully" one thing I do know
is  that in my work in both .net and java, XML plays a more significant
role. Everyone can probably speculate differently as to why this is. My
personal feeling is that it is because XML is less of a hassle than
building/passing around class hierarchies for application state in various
scenarios.But in python, it is far easier for me to pass around a dict or
some similar structure to get roughly the same effect. So in my mind, XML
solves a problem that is present in both .net and java, but not necessarily
python. In the same way, linq to xml solves the problem of handling xml in a
more convenient way.  In order for it to be useful in python, the problem
that xml solves would have to be present IMO.

That's not to say it's not possible. Someone who needs something like LINQ
to XML but in python could write something probably similar to what
sqlalchemy does and it would require no changes to the python language or
runtime. If it was written then maybe people would invent ways to use XML in
python that are better than what other things do. Hooray for the free market
of ideas. :)


This is all my opinion , I have no idea what the conventional wisdom of the
python community is on XML, but in my experience in other languages, it
seems to be the answer to a question that no one asked, or the wrong answer,
more often than it is the appropriate answer. Maybe it's only that way on
OHIO. :)




-- 
Thomas G. Willis
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python style: exceptions vs. sys.exit()

2008-09-24 Thread Ross Ridge
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> Presumably somebody has suggested that calling sys.exit() was a good 
> option. I'm curious to what possible reason they could give for such a 
> poor choice.

Grant Edwards  <[EMAIL PROTECTED]> wrote:
>Same here.  It's like an automotive engine controls designer
>asking if a failed O2 sensor should turn on the check engine
>light or blow up the car.

No, it's more like asking if the failed sensor should turn on a strange
and mysterious light on the dashboard and then blow up the car if the
driver doesn't immediately stop and check the engine.  The owners manual
would only vaguely hint at the fact that this could happen.

Ross Ridge

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


Re: Linq to Python

2008-09-24 Thread hrishy
Hi Tom

This is what i like and feel of the Python programmers smarter then every other 
langauge i know of.

But i am not comfortable with your second statement XML i never need it 
one day everybody would need it.


regards
Hrishy


--- On Tue, 23/9/08, Thomas G. Willis <[EMAIL PROTECTED]> wrote:

> From: Thomas G. Willis <[EMAIL PROTECTED]>
> Subject: Re: Linq to Python
> To: python-list@python.org
> Date: Tuesday, 23 September, 2008, 7:45 PM
> > But surely the idea behind it will eventually spread.
>  It's really
> > just comprehensions generalized over XML and
> relational datasets, a
> > noble goal.  Besides, it's main purpose for .NET
> was to bring
> > functional programming to it.  Python already has
> that, somewhat...
> 
> it's really any object out of the box, i think the sql
> linq stuff is
> more of a query compiler, IMO sqlalchemy does that.
> 
> 
> query = select(user_cols,
> 
> and_(table_relationship.c.accept_user_id==user.id,
> 
> table_relationship.c.start_date==None
> 
> ),
> 
> from_obj=join(
> 
> table_relationship,table_user,
> 
>
> onclause=table_user.c.id==table_relationship.c.init_user_id
> 
> ).outerjoin(table_profile)
> 
> )
> 
> session.execute(query).fetchall()
> 
> 
> 
> 
> 
> 
> XML? meh hopefully I would never need it. :)
> 
> 
> C# is my day job, and when I got my hands on LINQ back in
> January my
> initial thought was "Finally I have list
> comprehensions day job is
> fun again"
> 
> For the most part, I think C# is catching up.
> --
> http://mail.python.org/mailman/listinfo/python-list


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


Re: problem updating variable in a module

2008-09-24 Thread dudeja . rajat
Thanks Tim,

Yes, I mean 'mod' only.

But this does not work for me


On Wed, Sep 24, 2008 at 4:19 PM, Tim Rowe <[EMAIL PROTECTED]> wrote:

> 2008/9/24  <[EMAIL PROTECTED]>:
> > Hi,
> >
> > I've a problem updating my variable in a module.
> >
> > In my main program, I call a function from mod1 to update a variable of
> mod1
> > As soon as I update this varibale, I check it back in the mail program
> but
> > it the variable from mod1 does not get updated.
> >
> > main Program:
> > 
> > import mod1
> > a = 20
> > mod.update(a)
> > print mod.a   < does not print anything
> >
> > mod1
> > 
> > a = 10
> > def update(someInt):
> >  global a
> >  a = someInt
> >  print a < this does actually print a = 20
>
> I'm surprised it runs at all -- as far as I can see "mod" in
> "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"?
> If I change it to that, both print statements print "20" as I'd
> expect.
>
> I take it you do have a *really* good reason to use a global?
>
> --
> Tim Rowe
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

Re: Linq to Python

2008-09-24 Thread hrishy
Hi 

Well wouldn't it be a lot easier to query and join a xml source with a 
relational source with LINQ capabilites in Python.

Hmm what am i missing here is there a site that takes all LINQ examples and 
does them using list comprehensions and makes them sound easy ?

wasn't python supposed to make everything easy ?

regards
Hrishy


--- On Tue, 23/9/08, sturlamolden <[EMAIL PROTECTED]> wrote:

> From: sturlamolden <[EMAIL PROTECTED]>
> Subject: Re: Linq to Python
> To: python-list@python.org
> Date: Tuesday, 23 September, 2008, 7:49 PM
> On Sep 23, 4:48 pm, hrishy <[EMAIL PROTECTED]>
> wrote:
> 
> > Will LINQ be ported to Python ?
> 
> No, because Python already has list comprehensions and we
> don't need
> the XML buzzword.
> --
> http://mail.python.org/mailman/listinfo/python-list


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


Re: Linq to Python

2008-09-24 Thread hrishy
Hi Terry

Oops i never realised the mistake i have commited

I apologise 
(i thought changing the subject line would make a new thread)
I apologise
(I thought Python programmers were smart and they did know what LINQ was)
I don't apologise
( i dont apologise for the third one not sounding cocky here but i did google 
but nothing much came up thats when i posted the question here since i always 
see Python programmers are somehow smarter then programmers in other langauges 
i don't know if its the language or the programmers themselves that make them 
smart)

regards
Hrishy




--- On Tue, 23/9/08, Terry Reedy <[EMAIL PROTECTED]> wrote:

> From: Terry Reedy <[EMAIL PROTECTED]>
> Subject: Re: Linq to Python
> To: python-list@python.org
> Date: Tuesday, 23 September, 2008, 7:51 PM
> > Will LINQ be ported to Python ?
> 
> I have three suggestions:
> 
> 1. When starting a new thread, start a *new* thread. 
> Don't tack a new, 
> unrelated subject onto an existing thread.  Your post will
> not be seen 
> by people with readers that collapse thread and who do not
> happen to 
> read the 'Python is slow?' thread.
> 
> 2. Also, give enough informaton that people can understand
> your question 
> without searching the web and guessing.  In particular,
> that do *you* 
> mean by LINQ?  The game?  The .NET component? Or something
> else?
> 
> 3. Before posting, search the Python manuals or the web a
> bit for an 
> answer.  If you mean the .NET component, googling
> 'Python LINQ' should 
> partly answer your question.
> 
> tjr
> 
> --
> http://mail.python.org/mailman/listinfo/python-list


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


  1   2   >